home *** CD-ROM | disk | FTP | other *** search
/ ETO Development Tools 1 / ETO Development Tools 1.iso / Essentials / Developer Essentials Jul 90 / DTS Sample Code / Macintosh Sample Code / SC.024.SoundApp / SoundApp.p < prev    next >
Encoding:
Text File  |  1990-05-01  |  133.8 KB  |  3,473 lines  |  [TEXT/MPS ]

  1. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2. #
  3. # Apple Macintosh Developer Technical Support
  4. #
  5. # MultiFinder-Aware SoundApp Application
  6. #
  7. # SoundApp
  8. #
  9. # SoundApp.p - MPW 3.0/3.1 Pascal Source
  10. #
  11. # Jim Reekes - Macintosh Developer Technical Support
  12. # Copyright © 1989-1990 Apple Computer, Inc.
  13. # All rights reserved.
  14. #
  15. # Versions:
  16. #             1.03                    May, 1990
  17. #
  18. # Components:
  19. #             SoundApp.make        May 1, 1990            MPW build script
  20. #             SoundApp.p            May 1, 1990            Pascal source code
  21. #             SoundApp.r            May 1, 1990            Rez source code
  22. #             SoundAppSnds.r        May 1, 1990            Rez source code
  23. #             SoundUnit.p            May 1, 1990            Pascal source code
  24. #
  25. # Formatting was done with FONT = Monaco, SIZE = 9, TABS = 3
  26. #
  27. # many thanks to: Bo3b Johnson, Mark Bennett, Andy Shebanow, Keith
  28. # Rollin, Chris Derossi, Pete Helme, Darin Adler, and my co-workers that
  29. # sat near me while I was making lots of noise testing this application.
  30. #
  31. # To the reader,
  32. #
  33. # SoundApp.p is a sample application source file for demonstrating
  34. # the Sound Manager.  It requires the use of the SoundUnit to handle
  35. # all of the sound routines.  This portion of the source code handles the
  36. # application’s management of memory, errors, user interface, etc..
  37. # The read me notes are here in the source code because people tend to
  38. # not read them otherwise.
  39. #
  40. # SoundApp is a demonstration of the Sound Manager released in System
  41. # 6.0.x.  SoundApp is also a example of how to write a Macintosh
  42. # application that performs good user interface and proper error
  43. # handling.  Believe it or not, but the Sound Manager portion was the
  44. # easiest part for me to write.  It was all the user interface and error
  45. # handling that was the most difficult.  One thing became very clear to
  46. # me in the course of writing this application.  The following axiom is
  47. # one of the few great truths in the universe.
  48. #
  49. # If you write a Macintosh application without MacApp, you’re working
  50. # too hard.
  51. #
  52. # Throughout the development of SoundApp I would run into typical
  53. # situations that make programming a Macintosh too hard.  When this
  54. # happened I asked myself “what would MacApp do?” and that was followed
  55. # by the thought “then why am I writing code that is already out there
  56. # for me to use?”  I started out intending on writing a very simple
  57. # application that anyone could read, and understand the Sound Manager.
  58. # I felt this meant not requiring the person to read Object Oriented
  59. # Pascal.  I accomplished part of my goal.  People should be able to
  60. # learn how to use the Sound Manager (in its present condition), but it
  61. # didn’t turn out to be such a simple application as I had hoped for.
  62. #
  63. # I have put a large amount of comments into the code.  This is
  64. # something I’m really picky about.  People do not comment their code
  65. # enough.  Each procedure has a paragraph that should explain what to
  66. # expect that routine to do, and how it goes about doing it.  There are
  67. # some bigger issues that I will put into the release notes below.
  68. # There are some things that make the Macintosh harder to develop for
  69. # than it should be.  Simple things should be simple.  Too many things
  70. # on the Mac that should be simple are not.  Maybe someday these things
  71. # will be fixed.
  72. #
  73. # • GetFontInfo requires a port set to the font in question.  If I
  74. #   wanted to find the height of the System Font, I had to first set the
  75. #   current port to the WindowMgr.  I could have used my own window, but
  76. #   what if I needed the font info before I had a window available?
  77. # • The toolbox blows chunks when your heap gets “too low.”  I believe
  78. #   this magical number is between 32k and zero.  The odds of blowing
  79. #   chunks increase logarithmically as one approaches 0 free bytes.
  80. # • The Dialog Manager is not a free lunch and in fact will cost you
  81. #   plenty.
  82. # • There’s no safe way to determine how much memory opening a
  83. #   resource file will take away from your heap.
  84. # • There’s no way to determine how safe it is opening a resource that
  85. #   could be shared by other applications, especially on a local volume.
  86. # • The Resource Manager doesn’t always set ResErr.
  87. # • The Sound Manager returns even less errors.
  88. # • The List Manager returns no errors.
  89. # • Writing a staggering routine for new windows encompasses a number
  90. #   of difficulties.  How does one find the height of a window’s title
  91. #   region before the window is visible?
  92. #
  93. # Am I just a complainer?  Do I have a bad attitude?  Probably, but
  94. # I’m just trying to point out the above areas make the Mac programming
  95. # experience difficult.  These are areas that get developers into
  96. # trouble.  These areas need a sign in front of them that says,
  97. # “Danger!”  These are areas that developers get into and then write to
  98. # MacDTS for help.
  99. #
  100. # Notation Conventions
  101. # --------------------
  102. # All Pascal reserved words are in upper case.  All global variables
  103. # begin with a lower case “g”. All constants begin with “k” except for
  104. # those noted here.  Resource IDs begin with “r”.  Menu IDs being with
  105. # “m” and items with an “i”.  Resource strings begin with “s”.
  106. #
  107. # Human Interface
  108. # ---------------
  109. # This is the most important and about the most difficult aspect of
  110. # programming on the Macintosh.  In the development of SoundApp I gave much
  111. # thought to the human interface issues.  In fact, in talking with the Human
  112. # Interface Group additions to the existing guidelines were made.  The
  113. # method of window stacking used here was a new one.  This was documented in
  114. # a Human Interface Tech Note.  I even made one compromise (hard to
  115. # believe!) suggested by the Human Interface Group.  I originally had the
  116. # buttons and the list in my choice of font and size.  They felt that
  117. # buttons should be in the System font and the list should also be the same.
  118. # I liked my font choice better, but the group had a point that I really
  119. # couldn’t argue with.  That was, “If there isn’t a compelling reason to
  120. # change something standard, then don’t change it.”  Buttons on a Macintosh
  121. # typically appear in the System font.  Changing the font, just because I
  122. # wanted to, was considered gratuitous.  Standard File is in the System font
  123. # and it also contains a list and buttons.  Since my window are very similar
  124. # to that dialog, I’m using the System Font.
  125. #
  126. # SoundApp is never modal unless an error occurs and I need to show and
  127. # alert.  Controls are inactivated for inactive windows.  The default button
  128. # is given the proper outline, and this outline disappears when the window
  129. # is deactivated.  Keyboard equivalents for the buttons cause the button to
  130. # appear as if it had been clicked in.  The check box in the Standard File
  131. # dialog remembers the user’s last setting.  The about box is only
  132. # semi-modal.  It will allow the user access to switch to another application.
  133. # The status window under some circumstances was found to disappear too quickly,
  134. # so a built in delay was added.  Windows are centered or stacked according
  135. # to the Human Interface Guidelines.  The sound level isn’t adjusted by the
  136. # application, and instead the users is informed of the current level and
  137. # told how it can be adjusted.
  138. #
  139. # The About box
  140. # -------------
  141. # It’s rad.  Has a color icon, shows the 'vers' resource, goes Moof!™.  It
  142. # also demonstrates how to handle a modal window without the Dialog Manager.
  143. # This technique can be use for any window, including dialog windows.  The
  144. # dialog’s update routine would call UpdtDialog.  The really new point to
  145. # notice is this window is modal but ONLY within the application’s layer.
  146. # While running under MultiFinder, the user can switch to other
  147. # applications.  While the About window is present, it is the only window
  148. # belonging to the application that accepts user actions.
  149. #
  150. # Memory Management
  151. # ----------------
  152. # This has to be the most difficult portion of a Mac application to
  153. # write.  This along with the user interface.  I spent too many nights
  154. # chasing down crashes while running the application under low memory.
  155. # I found unpleasant surprises while doing this.  The Sound Manager
  156. # doesn’t check for NIL pointers.  OpenResFile may take large portions
  157. # of my heap away.  The toolbox seems to need at least 32k of free space
  158. # in the heap of my Mac II running color.
  159. #
  160. # I wrote a simple grow zone procedure that will dump a reserve memory
  161. # block.  This is only considered for use in an emergency.  I never rely
  162. # on using it directly.  If the reserve has been released, I will not
  163. # continue an operation such as playing a sound or showing the status
  164. # window until it is regained.  Grow zones should not be considered a
  165. # solution to memory management.  They can be used to augment your
  166. # overall memory management scheme.
  167. #
  168. # Error Checking
  169. # --------------
  170. # Lots and lots and lots of it.  I could even do more.  Programmers
  171. # need to do more of this.  The Sound Manager will crash when
  172. # encountering a NIL pointer.  My application should never crash.  If
  173. # you can find a way to crash this application, then I want to hear
  174. # about it.  Using a bogus 'snd ' resources doesn’t count and I’ve found
  175. # many of those.  Writing proper error checking into the code during
  176. # development really helped.  Always handle errors, and pass along the
  177. # error.  I will let the first error encountered to be passed all the
  178. # way up to the caller and eventually my error dialog will show up for
  179. # the user.
  180. #
  181. # SetPort Strategy
  182. # ----------------
  183. # Any routine that needs to use Quickdraw will set the port.  I do not
  184. # believe that it should also be responsible for restoring the port back
  185. # to what it may have been before the routine was called.  So, you’ll
  186. # find there is an absence of the GetPort, SetPort, do my thing, and
  187. # then SetPort again.  Instead I SetPort and do my thing.  The Mac often
  188. # is setting the port unnecessarily.
  189. #
  190. # Strings
  191. # -------
  192. # All of my strings are resources.  There are no strings that appear
  193. # within the code.  This helps memory management and allows me to adjust
  194. # the application to international systems without compiling any code.
  195. # I could simply use ResEdit, or some other tool, to localize this
  196. # application.  I find it is just as easy to run Rez again than
  197. # attempting to use ResEdit.  Besides, after editing with ResEdit I want
  198. # the source for that and would have to run DeRez which isn’t nearly as
  199. # clean as my original source files.
  200. #
  201. # Window Stacking
  202. # ---------------
  203. # I hate applications that will open a new document that covers up an
  204. # existing document, unless the new document covers the entire screen.
  205. # So, my application’s documents have a small window size.  I wanted to
  206. # open new windows that would not cover up older ones.  This is nice for
  207. # the user, since they will not have to move windows just to get at
  208. # other documents.  ResEdit will stagger new windows off of the
  209. # frontmost window but I find that this isn’t the best approach.  It
  210. # will still cover up other windows and I also don’t like windows that
  211. # will open half way between two monitors.  I wanted a better approach:
  212. # one that would always stagger new windows and not cover up older ones.
  213. #
  214. # When I want to center a window, I need to know its entire rectangle
  215. # size.  The rub is that I cannot determine its size until I show it
  216. # because I only know about the window’s boundsRect.  This does not
  217. # include the area that contains the title bar.  That’s the strucRgn,
  218. # which is an empty region for an invisible window.  I could do what
  219. # MacApp does, but if I have to do another thing that MacApp already
  220. # does I’ll give up and stick with MacApp.  I ended up writing a routine
  221. # that takes a guess at the height of the window’s title bar.  This is
  222. # another thing that was harder than it should have been.
  223. #
  224. # Dialog Manager (and some of the reasons I don’t like it)
  225. # --------------------------------------------------------
  226. # My first approach was to use modeless dialogs for document windows,
  227. # thinking that I could write an application that would demonstrate how to
  228. # deal with them and all of their idiosyncrasies.  Not long into the
  229. # development cycle it became obvious to me that I was fighting something
  230. # that contained more disadvantages than advantages.  I removed all the
  231. # dialog code and only used standard windows and controls the old fashion
  232. # way.  In the case of the About window, which is semi-modal, I have a test
  233. # that will return TRUE for a window that should be treated as modal.  This
  234. # allows my window to be handled by my standard event handlers and I don’t
  235. # have to write dialog filters.  There are some things that do not get
  236. # handled properly while calling ModalDialog.  ModalDialog ignores disk
  237. # insert events.  The activate or update events do not get handled for
  238. # background windows.  Using a modeless dialog fails with MultiFinder if
  239. # switching takes place while the dialog is the frontmost window.  The
  240. # problem is that DialogSelect ignores and removes the suspend/resume event.
  241. # Another advantage to all this is that drawing was much faster.
  242. #
  243. # As an example of some of the problems with ModalDialog and the activate
  244. # event.  Try this with the Finder.  Open a window and choose “View by name.”
  245. # Then select a few names with the shift key and resize the window so the
  246. # vertical scroll bar is visible.  Move this window to one edge of the
  247. # screen or a second monitor.  Now choose “Set Startup.”  This is a modal
  248. # dialog.  If you look at the Finder window with the selected files, you’ll
  249. # notice that the scrollbar and the text are still highlited.  This is not
  250. # the proper user interface.  This is because the deactivate routines are
  251. # not called while in ModalDialog.  You can even find this problem with
  252. # SoundApp.  On deactivate events I will change my controls to the inactive
  253. # state.  If you place the buttons to the side of the screen and then bring
  254. # up the standard file dialog, you’ll notice that the buttons don’t change
  255. # properly.  ModalDialog also prevents the application from updating
  256. # background windows too.  To solve this a dialog filter procedure is
  257. # required.  In most cases, this filter would be as complex and the event
  258. # loop.  It would also make it necessary to call your event routines from
  259. # outside of the normal event loop.  All on this isn’t worth the effort.
  260. #
  261. # You can see how this does not happen while using this application’s
  262. # About window.  Select an item in the document window and choose “Play
  263. # Melody.”  This will leave the status window on screen so that you can
  264. # drag it to cover the document window.  Now select “About SoundApp” to
  265. # bring up the about window.  This causes the status window to close,
  266. # which uncovers the document window leaving an invalid area.  The
  267. # document window gets an activate event, then the About window appears.
  268. # Then the document window is properly deactivated and updated.  Yeah,
  269. # just like it should happen.
  270. #
  271. # So, the tradeoff was that I didn’t have to work around all the
  272. # strange things the Dialog Manager does such as running a secondary
  273. # event loop, and requiring me to have userItems or filterProcs.  This
  274. # made the code smaller, more readable, and faster.  I think I will
  275. # avoid the Dialog Manger from now one unless I’m using a very simple
  276. # dialog.  The about window of this application proved too much for the
  277. # Dialog Manager.
  278. #
  279. # One thing dialogs are good for is running ResEdit and laying out the
  280. # dialog.  To help position controls, I used a DLOG resource of the same
  281. # size as my WIND resource.  The DITL of this dialog contains the
  282. # positions I wanted for my CNTL resources.  This helped me to look at
  283. # where I could expect my buttons to show up.  This is one of the main
  284. # reasons people think they need the Dialog Manager, because ResEdit
  285. # makes it easy to build dialogs.  ResEdit alone has contributed to
  286. # nearly all of the Dialog Manager abuse in the world today.
  287. #
  288. # I used a Rect resource for positioning the list rectangle of the
  289. # document windows.  These windows look very much like a modeless
  290. # dialog.  (They used to be, but that presented to many problems.)  The
  291. # About window is also a standard window, but shown modally.  Just like
  292. # ModalDialog, but my modal window does allow switching under
  293. # MultiFinder.  You can change the window to a dBoxProc and then
  294. # MultiFinder will not switch while this is the active window.  To help
  295. # with the layout of the about window, I position the text within it
  296. # based on the size of the window.  The status window does this too.
  297. # These two things, the Rect resource and text based on the size of the
  298. # window, help when changing the text.  If the new text doesn’t fit,
  299. # then resize the window’s resource.  I used some trick with Rez to help
  300. # layout my window contents.  Refer to the SoundApp.r sources.
  301. #
  302. # I’ve read and understood Tech Note #203, and have learned how to
  303. # apply it.  Bo3b Johnson is a smart guy, and developers should trust
  304. # his opinions.
  305. #
  306. # List Manager
  307. # ------------
  308. # It’s very easy to be tempted by this part of the toolbox, along with
  309. # the Dialog Manager.  The List Manager is a slow beast at times.  It
  310. # also has some problems with “doing the right thing.”  I’ve found that
  311. # the list will not be updated properly when the user clicks in a cell
  312. # that is out of bounds.  LClick will return TRUE with a cell that
  313. # doesn’t exists.  LActivate will erase the scrollbars instead of
  314. # highlighting the properly.  Finally, the List Manager does not return
  315. # errors.  How would a person know if LSetCell worked?
  316. #
  317. # I’ve read and understood Tech Note #203, and have learned how to
  318. # apply it.
  319. #
  320. # Resource Manager
  321. # ----------------
  322. # I test all the handles being returned from the Resource Manager
  323. # before using them, and if I get a NIL then I look at ResError.
  324. # ResError sometimes lies and returns noErr and a NIL handle.  ResError
  325. # is usually good for getting an error code AFTER you’ve already found
  326. # an error.
  327. #
  328. # Opening a resource file that is already open by another application
  329. # is dangerous.  The Resource Manager will not tell you when you’ve done
  330. # this.  There needs to be a OpenRFPerm that will return permission
  331. # errors such as resFileBusyErr.  Refer to Tech Note #185.
  332. #
  333. # When I or the Toolbox needs to get at one of my resources,
  334. # CurResFile must be set to my application.  Also, look out for one
  335. # particularly nasty situation when switching resource files.   If the
  336. # segment loader goes for a CODE segment, it better be from our resource
  337. # file!  The idea here is, in case you didn’t get it already, always
  338. # have the current resource file be set to the application.  If a
  339. # resource is needed from another file, switch momentarily to get the
  340. # resource and immediately restore the current resource file to the
  341. # application.  I take an added measure of defense and whenever I need a
  342. # resource I use the Get1Resource calls.  These will only search the
  343. # current resource file.
  344. #
  345. # Strategies For Sound
  346. # --------------------
  347. # All of the Sound Manager code is contained in the SoundUnit.p.  This
  348. # unit was written to be general purpose, providing useful routines for
  349. # other applications.  Lots of error checking is performed.  I’ve also
  350. # extended the support for SndPlay and made it really asynchronous.
  351. # I’ve demonstrated most of the abilities the present Sound Manager has
  352. # to offer.  I will have to revise the SoundAppUnit to include any new
  353. # features (e.g., multi channel support) when the next Sound Manager is
  354. # released.
  355. #
  356. # I allocate my own memory to be used as sound channels.  I allocate
  357. # these pointers early in the application’s startup time to avoid memory
  358. # fragmentation.  These channels are of the standard size (holding 128
  359. # commands) but I’ve extended the structure to include my own
  360. # information.  When I create a new sound channel, I pass it a pointer
  361. # to this memory.  This will link in the 'snth' resource and hardware to
  362. # my channel.  When I dispose of the channel, the Sound Manager will
  363. # purge this resource and disconnect me from the hardware.  When adding
  364. # the 'snth' resource, the Sound Manager will allocate a pointer into
  365. # the application’s heap instead of the system’s.  This is a modifier
  366. # stub used by the 'snth'.  This could cause some problems with memory
  367. # management.  I create and dispose of all my channels as soon as
  368. # possible, and this doesn’t cause me problems.
  369. #
  370. # I keep track of which document is playing a sound, along with a
  371. # global of when the application is playing sound.  I needed to keep
  372. # track of which document is playing because if the user disposes of
  373. # that document, I will have to stop playing the sound contained in it
  374. # since the user wants to dispose of that data.  I keep track of when
  375. # the application is playing sound in a global.  This is only used by
  376. # the routine that calculates the sleep time for WaitNextEvent.
  377. #
  378. # I came up with a pretty sick music notational system using Rez.
  379. # Refer to the notes in the SoundAppSnds.r file.  If you’ve just
  380. # finished a meal, wait four hours before reading.
  381. #
  382. # The SoundUnit handles all of the Sound Manager code entirely.  This
  383. # eliminates any and all references to the Sound Manager from the
  384. # application.  The SoundUnit will return any error encountered while
  385. # calling the Sound Manager, and does some extra error checking the
  386. # Sound Manager doesn’t do.
  387. #
  388. # The portion of the application that uses the wave table synthesizer
  389. # is more complex than the other two.  I wanted to include an example
  390. # channel modifier for use in the wave table channels.  This would have
  391. # been a transpositional modifier that would take a given noteCmd and
  392. # transpose it by some amount.  This would be nice for the routine that
  393. # plays a scale, by allowing the other three channels to be playing the
  394. # same scale but at a different interval.  Unfortunately, I found that
  395. # the Sound Manager has bugs using a modifier, at least with the wave
  396. # table synths, and could not use them.
  397. #
  398. # I’ve created a few wave table sounds and keep them in a 'snd '
  399. # resource.  This allows me to change the sound of the wave table
  400. # channels and not change any of the code.  Creating wave table data is
  401. # complicated.  The example sounds I’ve included are samples I’ve taken
  402. # from various sources.  I’ve cleaned them up quit a bit.  This was to
  403. # set loop points, try and reduce clicks, correct the sample rates, and
  404. # base notes.  This is also a complicated task.  Maybe I should document
  405. # these techniques.
  406. #
  407. # Jim Reekes E.O., Macintosh Developer Technical Support
  408. # Tuesday, January 30, 1990  1:01 PM
  409. #
  410. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  411.  
  412. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  413. PROGRAM SoundApp;
  414. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  415.  
  416. {I’m purposely avoiding the use of the interface files OSIntF and PackIntf.
  417.  These two files include lots of others, some of which I don’t need.
  418.  By avoiding the use of these files, compile times are faster.  It helps
  419.  cut down on the symbol table thrashing by loading unnecessary files.
  420.  Anything to help MPW go faster!  I could also avoid ToolIntf, but in my
  421.  application I’m using all of the files it includes.}
  422.  
  423. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  424. USES
  425. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  426.     Types, QuickDraw, Traps, ToolIntf, Files, SegLoad, Packages, Menus,
  427.     OSEvents, DiskInit, SysEqu, Script, Errors, CursorCtl, Sound, SoundUnit;
  428.  
  429. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  430. CONST
  431. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  432.     kSysEnvironsVersion =    1;        {Version of the SysEnvRec I understand.}
  433.     kSystem602 =            $0602;    {SysEnvRec value for System version 6.0.2}
  434.     kPollingSleepTime =    60;        {MultiFinder’s sleep while sound is playing}
  435.  
  436.     kNumberOfMasters =     3;            {number of master pointer blocks we expect}
  437.     kSizeOfReserve =        32 * 1024; {size of reserve memory for grow zone proc}
  438.     kMinSpace =                32 * 1024; {minimum available memory I allow in heap}
  439.     kMemForSndDoc =        20 * 1024; {minimal amount of memory needed by document}
  440.  
  441.     kScrollBarWidth =        15;        {the width of the scrollbar in the list}
  442.     kListFrameInset =        -1;        {inset rectangle adjustment for list frame}
  443.     kMsgInset  =            8;            {inset rectangle adjustment for messages}
  444.  
  445.     kSFTop =                    40;        {top of Standard File and DIBadMount dialog}
  446.     kSFLeft =                50;        {left of Standard File and DIBadMount dialog}
  447.  
  448.     kCntlActivate =        0;            {enabled control’s hilite state}
  449.     kCntlDeactivate =        255;        {disabled control’s hilite state}
  450.     kSelect =                1;            {select the control}
  451.     kDeselect =                0;            {deselect the control}
  452.     kCntlOn =                1;            {control’s value when truned on}
  453.     kCntlOff =                0;            {control’s value when truned off}
  454.  
  455.     kButtonFrameSize =    3;            {button’s frame pen size}
  456.     kButtonFrameInset =    -4;        {inset rectangle adjustment around button}
  457.     kButtonSizeH =            17;        {standard height of buttons}
  458.     kDafaultButSizeH =     kButtonSizeH - kButtonFrameInset - kButtonFrameInset;
  459.  
  460.     kIconTop =                10;        {standard position for icons in alerts}
  461.     kIconLeft =                20;
  462.     kIconBot =                42;
  463.     kIconRight =            52;
  464.     kIconPictGap =            8;            {pict spacing in about window}
  465.  
  466.     kFSAsynch =                TRUE;        {asynchronous File Manager call}
  467.  
  468.     kEnterKey =                CHR($03); {the keys I’m looking for}
  469.     kReturnKey =            CHR($0D);
  470.     kEscape =                CHR($1B);
  471.     kUpArrow =                CHR($1E);
  472.     kDownArrow =            CHR($1F);
  473.     kPeriod =                CHR($2E);
  474.  
  475. {This bit set in the ioFlAttrib field if the file’s resource fork is open.}
  476.     kResForkOpenBit =        2;
  477.  
  478. {For the delay time when flashing the menubar and highlighting a button.}
  479.     kDelayTime =            8;            {8/60ths of a second}
  480.  
  481. {The lowest volume I consider before suggesting the user increase it.}
  482.     kMinVolumeDesired =    4;
  483.  
  484. {BUG NOTE: Using a timbre value of 255 on the Mac Plus/SE will cause a crash.}
  485.     kSquareWave =            240;         {square wave for note synthesizer}
  486.     kSineWave =                0;            {sine wave for the note synthesizer}
  487.     kPreferredTimbre =    190;        {my preferred timbre for the note synthesizer}
  488.  
  489. {The following constants are the resource IDs.}
  490.     rMenuBar =                1000;        {application’s menu bar}
  491.  
  492.     rExitAlert =            1000;        {emergency exit user alert}
  493.     rUserAlert =            1001;        {error message user alert}
  494.     rSoundVolAlert =        1002;        {sound is set low alert}
  495.  
  496.     rSFPGetFileDLOG =        -4000;    {dialog template for SFPGetFile}
  497.     rSndOnlyCheckBox =    11;        {dialog item number in SFPGetFile}
  498.  
  499. {These are the window IDs used in the applications.  Each one must be unique,
  500.  since they are used to identify which window the event took place in.}
  501.     rAboutWindow =            1000;        {about window}
  502.     rStatusWindow =        1001;        {sound status window}
  503.     rSoundWindow =            1002;        {sound document window}
  504.  
  505.     rListRectID =            1000;        {resource containing size of list rectangle}
  506.  
  507.     rCancelCntl =            1000;        {stop button ID for the status window}
  508.     rPlaySndCntl =            1001;        {sound button IDs for the sound document window}
  509.     rHyperPlayCntl =        1002;
  510.     rPlayScaleCntl =        1003;
  511.     rMelodyCntl =            1004;
  512.     rStopCntl =                1005;
  513.     rAboutOkCntl =            1006;
  514.     rUntitled =                1000;        {string ID for untitled resources}
  515.     rAboutText =            1001;        {string ID for text appearing in about window}
  516.     rMoofIcon =                1000;        {resource ID for ICON of application}
  517.     rAppPict =                1000;        {resource ID of picture shown in about window}
  518.     rSndCursor =            1000;        {cursor resource for our documents}
  519.  
  520. {The following are the snd resource IDs contained in the application,
  521.  which start at ID 9000.  IDs 0 - 8191 are reserved for Apple.}
  522.     rMoofSound =            9000;        {snd for the about window}
  523.     rScaleSnd =                9001;        {snd containing a scale}
  524.     rMelodyPart1 =            9002;        {snd containing a melody}
  525.     rMelodyPart2 =            9003;        {snd containing the harmony}
  526.     rMelodyPart3 =            9004;        {snd containing the harmony}
  527.     rMelodyPart4 =            9005;        {snd containing the harmony}
  528.     rWaveHarmony =         9006;        {snd containing waveTable for harmony}
  529.     rWaveMelody =             9007;        {snd containing waveTable for melody}
  530.     rCounterPt1    =            9008;        {snd containing soprano part of counter point}
  531.     rCounterPt2 =            9009;        {snd containing alto part of counter point}
  532.     rCounterPt3 =            9010;        {snd containing tenor part of counter point}
  533.     rCounterPt4 =            9011;        {snd containing bass part of counter point}
  534.     rSopranoVox =             9012;        {snd containing waveTable of soprano voice}
  535.     rAltoVox =                9013;        {snd containing waveTable of alto voice}
  536.     rTenorVox =                9014;        {snd containing waveTable of tenor voice}
  537.     rBassVox =                9015;        {snd containing waveTable of bass voice}
  538.  
  539. {The following are resource IDs for messages.}
  540.     sErrStrings =            1000;        {error string STR# ID}
  541.     sStandardErr =            1;            {An error has occurred.}
  542.     sMemErr =                2;            {A Memory Manager error has occurred.}
  543.     sResErr =                3;            {A Resource Manager error has occurred.}
  544.     sCurInUseErr =            4;            {That file is currently in use.}
  545.     sWavesBroken =            5;            {The wave table synthesizer is not available.}
  546.     sWrongVersion =        6;            {This system does not support the Sound Manager...}
  547.     sLowMemory =            7;            {Memory is too low to continue...}
  548.     sNoMenus =                8;            {Could not find application’s menu resources.}
  549.     sInitSoundErr =        9;            {Could not initialize the Sound unit.}
  550.     sSoundErr =                10;        {The Sound Manager has encountered an error.}
  551.     sNewDocErr =            11;        {Could not create a new document.}
  552.     sInitStatusErr =        12;        {Error initializing the status window.}
  553.     sNoSndsErr =            13;        {This file does not contain any sound resources.}
  554.  
  555.     sMsgStrings =            1001;        {message string STR# ID}
  556.     sPlayingMsg =            1;            {playing a sound}
  557.     sHyperMsg =                2;            {playing a sound the Hyper way}
  558.     sScaleMsg =                3;            {playing scale}
  559.     sMelodyMsg =            4;            {playing melody}
  560.     sTimbresMsg =            5;            {playing various timbres}
  561.     sCounterPtMsg =        6;            {playing 4 part counter point}
  562.  
  563.     sSMErrStrings =        1002;        {strings describing Sound Manager errors}
  564.  
  565. {The following constants are used to identify menus and items. The menu IDs
  566.  have an “m” prefix and the item numbers within each menu have an “i” prefix.}
  567.     mApple =                    128;        {Apple menu and items}
  568.     iAbout =                    1;
  569.  
  570.     mFile =                    129;        {File menu and items}
  571.     iNew =                    1;
  572.     iOpen =                    2;
  573.     iClose =                    4;
  574.     iQuit =                    12;
  575.  
  576.     mEdit =                    130;        {Edit menu and items}
  577.     iUndo =                    1;
  578.     iCut =                    3;
  579.     iCopy =                    4;
  580.     iPaste =                    5;
  581.     iClear =                    6;
  582.  
  583.     mDemos =                1000;            {Demos menu and items}
  584.     iNoteScale =            1;
  585.     iNoteMelody =            2;
  586.     iNoteTimbre =            3;
  587.     iWaveScale =            5;
  588.     iWaveMelody =            6;
  589.     iWaveSATB =                7;
  590.  
  591. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  592. TYPE
  593. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  594.  
  595.     BooleanPtr =        ^BOOLEAN;            {Ptr to a BOOLEAN, for type coercion}
  596.     IntegerPtr =        ^INTEGER;            {Ptr to a INTEGER, for type coercion}
  597.     LongIntPtr =        ^LongInt;            {Ptr to a LONGINT, for type coercion}
  598.     RectPtr =            ^Rect;                {Ptr to a Rect resource for coercion}
  599.     RectHandle =        ^RectPtr;            {Handle to a Rect resource for coercion}
  600.  
  601. {This is a document layout that contains the window record and references
  602.  to the associating data.  The window record MUST be the first field.  This
  603.  is because I use the window pointer returned by the Toolbox to be a
  604.  pointer to my document.  To confirm that the window pointer is a document
  605.  pointer, I store an application reference in the window record’s refCon.
  606.  Then, I use a routine to test for the presence of this reference to insure
  607.  I’m looking at one of my document’s windows.}
  608.  
  609.     SndDocument =     RECORD
  610.         window:        WindowRecord;            {must be first field}
  611.         resFile:        INTEGER;                    {document’s resource file}
  612.         vRefNum:        INTEGER;
  613.         dirID:        LONGINT;
  614.         list:            ListHandle;                {document’s list of sounds}
  615.         sndInUse:    BOOLEAN;                    {document is using a 'snd ' resource}
  616.     END;
  617.     SndDocPeek =    ^SndDocument;            {to peek at the document record}
  618.  
  619. {This is the status window layout.  The concept here is similar to the
  620.  document type mentioned above.  The message is a string handle used to
  621.  store the current message.}
  622.  
  623.     StatusWindow = RECORD
  624.         window:        WindowRecord;
  625.         message:        StringHandle;            {current text of status message}
  626.         showTime:    LONGINT;                    {time window was shown}
  627.     END;
  628.     StatWindowPeek = ^StatusWindow;
  629.  
  630. {This is the about window layout.  The concept here is similar to the
  631.  document type mentioned above.  The message is a string handle used to
  632.  store the current message.}
  633.  
  634.     AboutWindow =    RECORD
  635.         window:        WindowRecord;
  636.         comment:        Handle;                    {handle to string of about comments}
  637.         appIcon:        Handle;                    {handle to icon or color icon}
  638.         iconIsColor:Boolean;                    {TRUE if above icon is color}
  639.         appPict:        Handle;                    {handle to picture of app’s name}
  640.     END;
  641.     AboutWPeek =    ^AboutWindow;
  642.  
  643. {This is the template to the WIND resource.  I used it to load in the WIND
  644.  resource and then adjust the boundsRect.  I also look at the procID to
  645.  determine if it has a title bar or drag region.}
  646.  
  647.     WindowTemplate =    RECORD                {template to a WIND resource}
  648.         boundsRect:    Rect;
  649.         procID:        INTEGER;
  650.         visible:     BOOLEAN;
  651.         filler1:     BOOLEAN;
  652.         goAwayFlag: BOOLEAN;
  653.         filler2:     BOOLEAN;
  654.         refCon:        LongInt;
  655.         title:        Str255;
  656.     END;
  657.     WindowTPtr =    ^WindowTemplate;
  658.     WindowTHndl =    ^WindowTPtr;
  659.  
  660. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  661. VAR {The “g” prefix is used to emphasize that a variable is global.}
  662. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  663.  
  664. {gMac is used to hold the result of a SysEnvirons call. This makes it
  665.  convenient for any routine to check the environment. It is considered
  666.  global information, anyway.}
  667.  
  668.     gMac:                        SysEnvRec;        {set up by Initialize}
  669.  
  670. {gReserveMemory is a handle of reserve memory used by my grow zone
  671.  procedure.  If memory is attempted to be allocated and fails, my grow
  672.  zone will release this reserved block of memory.}
  673.  
  674.     gReserveMemory:        Handle;
  675.  
  676. {gStatusWindow is the window that tells the user what’s happening.  I show
  677.  it while a sound is playing, and remove it as soon as the sound is
  678.  complete.  It is initialized once during startup, and from then on two
  679.  routines are used to show and hide it.  This demonstrates orchestrating
  680.  multimedia, that sound/graphic idea, at least in a crude sort of way.}
  681.  
  682.     gStatusWindow:            StatWindowPeek;
  683.  
  684. {gAppResRef is the application’s resource file reference.  I need to save
  685.  this since I can open other resource files.  The current resource file is
  686.  always gAppResRef unless I momentarily set it to another file to read its
  687.  resources, and then immediately restore it back.}
  688.  
  689.     gAppResRef:             INTEGER;            {set up by Initialize}
  690.  
  691. {gInBackground is maintained by our osEvent handling routines. Any part of
  692.  the program can check it to find out if it is currently in the background.}
  693.  
  694.     gInBackground:         BOOLEAN;            {maintained by Initialize and DoEvent}
  695.  
  696. {gSndFilesOnly is used to determine if the check box in the custom
  697.  SFPGetFile dialog has been chosen.  If this is true, then I want to only
  698.  show files that contain 'snd ' resources.}
  699.  
  700.     gSndFilesOnly:            BOOLEAN;            {maintained by SFGetHook}
  701.  
  702.  
  703. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  704. { IMPLEMENTATION }
  705. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  706. {$S Main}
  707. FUNCTION MyGrowZone(cbNeeded: Size): LONGINT;
  708.  
  709. {This is a very basic grow zone procedure.  My application keeps a reserve
  710.  handle of memory in case the Memory Manager gets a request for some memory
  711.  that is not available in my heap.  If memory were to get tight (<32k),
  712.  the Toolbox will crash the system, especially Quickdraw.  Before releasing
  713.  the reserve handle I make sure it isn’t the GZSaveHnd.  This handle cannot
  714.  be touched by the grow zone procedure.
  715.  
  716.  WARNING:  The grow zone procedure will be called and A5 may not be valid.
  717.  Read Tech Note #136 and 208}
  718.  
  719. VAR
  720.     theA5:         LONGINT;
  721.  
  722. BEGIN
  723.     theA5:= SetCurrentA5;
  724.     IF (gReserveMemory^ <> NIL) & (gReserveMemory <> GZSaveHnd) THEN BEGIN
  725.         EmptyHandle(gReserveMemory);
  726.         MyGrowZone:= kSizeOfReserve;                {released this much memory}
  727.     END ELSE
  728.         MyGrowZone:= 0;                                {this may release more memory}
  729.     theA5:= SetA5(theA5);
  730. END; {MyGrowZone}
  731.  
  732. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  733. {$S Main}
  734. FUNCTION LowOnReserve: BOOLEAN;
  735.  
  736. VAR
  737.     total, contig:            LONGINT;
  738.  
  739. {Before my application attempts to use more memory, I call this routine
  740.  to check if I’m already using my reserve memory.  If so, then I better
  741.  prepare to die or get my reserve back.}
  742.  
  743. BEGIN
  744.     LowOnReserve:= gReserveMemory^ = NIL;        {empty handle is low reserve}
  745. END; {LowOnReserve}
  746.  
  747. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  748. {$S Main}
  749. PROCEDURE RecoverReserve;
  750.  
  751. {This is called from the event loop if LowOnReserve returns that I’m out of
  752.  the reserve memory.  This will recover the reserve memory block.  If this
  753.  fails, it will be called the next time through the event loop.}
  754.  
  755. BEGIN
  756.     ReallocHandle(gReserveMemory, kSizeOfReserve);
  757. END; {RecoverReserve}
  758.  
  759. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  760. {$S Initialize}
  761. FUNCTION AllocateReserve: BOOLEAN;
  762.  
  763. {This is called at startup time to allocate the reserve memory block used
  764.  in the grow zone procedure.  If I’m unable to obtain this reserve, then
  765.  return FALSE to signal a failure.}
  766.  
  767. BEGIN
  768.     gReserveMemory:= NewHandle(kSizeOfReserve);
  769.     AllocateReserve:= gReserveMemory <> NIL;
  770. END; {AllocateReserve}
  771.  
  772. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  773. {$S Main}
  774. FUNCTION FailLowMemory(memRequest: LONGINT): BOOLEAN;
  775.  
  776. {Call PurgeSpace and see if the requested amount of memory exists in the
  777.  heap including a minimal amount of heap space.  Also, if my grow zone’s
  778.  reserve has been release, that’s considered a failure.  I don’t perform
  779.  any purging here.  The Memory Manager will do this if it needs the space.
  780.  This routine can be called with a memRequest = 0.  This checks if the heap
  781.  space is getting critical.}
  782.  
  783. VAR
  784.     total, contig:        LONGINT;
  785.  
  786. BEGIN
  787.     PurgeSpace(total, contig);
  788.     FailLowMemory:= (total < (memRequest + kMinSpace)) | LowOnReserve;
  789. END; {FailLowMemory}
  790.  
  791. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  792. {$S Main}
  793. FUNCTION HasSelection(sndDoc: SndDocPeek): BOOLEAN;
  794.  
  795. {This a simple test to see if the user has a currently selected list item.}
  796.  
  797. VAR
  798.     aCell:            Cell;
  799.  
  800. BEGIN
  801.     SetPt(aCell, 0, 0);
  802.     HasSelection:= LGetSelect(TRUE, aCell, sndDoc^.list)
  803. END; {HasSelection}
  804.  
  805. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  806. {$S Main}
  807. FUNCTION GetSelection(sndDoc: SndDocPeek; VAR sndHandle: Handle): OSErr;
  808.  
  809. {Given a document, this will find the currently selected cell in the list.
  810.  Then using this cell as an index number, I call Get1IndResource.  This
  811.  will return the proper handle.  Since the List Manager is zero based and
  812.  the Resource Manager isn’t, I have to add one to the index.
  813.  
  814.  BUG NOTE: GetIndResource will return a bogus handle if the index is not
  815.  positive.}
  816.  
  817. VAR
  818.     aCell:             Cell;
  819.  
  820. BEGIN
  821.     GetSelection:= noErr;
  822.     SetPt(aCell, 0, 0);
  823.     IF LGetSelect(TRUE, aCell, sndDoc^.list) THEN BEGIN
  824.         IF aCell.v > -1 THEN BEGIN                {GetIndResource doesn’t like < 0}
  825.             UseResFile(sndDoc^.resFile);        {only get our resources}
  826.             sndHandle:= Get1IndResource('snd ', aCell.v + 1);
  827.             IF sndHandle = NIL THEN
  828.                 GetSelection:= ResError;        {return any error}
  829.             UseResFile(gAppResRef);                {restore our resource file}
  830.         END;
  831.     END;
  832. END; {GetSelection}
  833.  
  834. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  835. {$S Main}
  836. PROCEDURE SelectNextCell(list: ListHandle; next: BOOLEAN);
  837.  
  838. {This is used to allow the user to select items from the list by using
  839.  the arrow keys.  Given a list and the direction, this will select the
  840.  next cell.  It will do nothing if we’re at the first cell and the user
  841.  wants to do even higher (sped), or if we’re at the last cell and the
  842.  user wants to go even lower (rent a clue bud).}
  843.  
  844. VAR
  845.     aCell:            Cell;
  846.     lastItem:        INTEGER;
  847.  
  848.     PROCEDURE DoNextSelection;
  849.     BEGIN
  850.         LSetSelect(FALSE, aCell, list);
  851.         IF next THEN
  852.             aCell.v:= aCell.v + 1
  853.         ELSE
  854.             aCell.v:= aCell.v - 1;
  855.         SetPt(aCell, aCell.h, aCell.v);
  856.         LSetSelect(TRUE, aCell, list);
  857.         LAutoScroll(list);
  858.     END;
  859.  
  860. BEGIN
  861.     lastItem:= list^^.dataBounds.bottom - 1;        {bounds is 1 greater}
  862.     SetPt(aCell, 0, 0);
  863.     IF LGetSelect(TRUE, aCell, list) THEN BEGIN
  864.         IF (next & (aCell.v < lastItem)) | ((NOT next) & (aCell.v > 0)) THEN
  865.             DoNextSelection;
  866.     END ELSE                                                    {if no cells selected...}
  867.         LSetSelect(TRUE, aCell, list);                {select the first cell}
  868. END; {SelectNextCell}
  869.  
  870. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  871. {$S Open}
  872. FUNCTION OpenByApp(vRefNum: INTEGER; dirID: LONGINT;
  873.                         fName: StringPtr; VAR window: WindowPtr): BOOLEAN;
  874.  
  875. {In the case that the user has attempted to open a resource file that is
  876.  already open, this routine will scan my open documents for it.  If I find
  877.  that the requested file is already open by the application, then return
  878.  true and its window pointer.  The application can then simply select that
  879.  window.  If the resource file is open but not by this application, that’s
  880.  a problem and I don’t use the resource file.  Many problems with using an
  881.  open resource file.  Now if the Resource Manager would take care of this
  882.  problem for us...}
  883.  
  884. VAR
  885.     docName:                    Str255;
  886.     testWindow:                WindowPtr;
  887.  
  888. BEGIN
  889.     OpenByApp:= FALSE;
  890.     testWindow:= FrontWindow;
  891.     WHILE testWindow <> NIL DO BEGIN
  892.         IF GetWRefCon(testWindow) = rSoundWindow THEN
  893.             IF (vRefNum = SndDocPeek(testWindow)^.vRefNum)
  894.              & (dirID = SndDocPeek(testWindow)^.dirID) THEN BEGIN
  895.                  GetWTitle(testWindow, docName);
  896.                 IF fName^ = docName THEN BEGIN
  897.                     window:= testWindow;
  898.                     OpenByApp:= TRUE;
  899.                     EXIT(OpenByApp);
  900.                 END;
  901.             END;
  902.         testWindow:= WindowPtr(WindowPeek(testWindow)^.nextWindow);
  903.     END;
  904. END; {OpenByApp}
  905.  
  906. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  907. {$S Main}
  908. FUNCTION GetGlobalMouse: Point;
  909.  
  910. {Get the global coordinates of the mouse.  Get the global coordinates by
  911.  calling GetMouse and LocalToGlobal.  This assumes the current port is a
  912.  valid graf port.  When wouldn’t it be?}
  913.  
  914. VAR
  915.     globalPt:        Point;
  916.  
  917. BEGIN
  918.     GetMouse(globalPt);
  919.     LocalToGlobal(globalPt);
  920.     GetGlobalMouse:= globalPt;
  921. END; {GetGlobalMouse}
  922.  
  923. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  924. {$S Open}
  925. FUNCTION GetWTitleHeight(variant: INTEGER): INTEGER;
  926.  
  927. {Try and determine the window’s title bar height.  This isn’t easy,
  928.  especially if the window is invisible.  We all know how the standard Apple
  929.  System WDEF works, at least at this date we do.  I assume that method as
  930.  shown below.  I could do what MacApp does with the Function CallWDefProc.
  931.  If the user has installed a replacement for the System WDEF, then it’s
  932.  their problem to deal with.  My method will work as long as Apple doesn’t
  933.  change how the WDEF in System 6.0 calculates the title bar height.  This
  934.  will allow my application to work on international Macs that have a larger
  935.  system font than Chicago.  I check the window’s variant code for one that
  936.  includes a title bar.  I will have to change this routine to adjust for
  937.  the modal-moveable window type, which hasn’t been defined yet.
  938.  
  939.  In this routine, I violate my rule about not using the GetPort, SetPort,
  940.  SetPort sequence mentioned at the start of the file. Mostly, I do this
  941.  because it’s not all that apparent that a routine called GetWTitleHeight
  942.  will change the port, so I make sure that it doesn’t.}
  943.  
  944. VAR
  945.     info:                FontInfo;
  946.     curGraf,
  947.     wMgrPort:        GrafPtr;
  948.     wTitleHeight:    INTEGER;
  949.  
  950. BEGIN
  951.     IF variant IN [documentProc, noGrowDocProc,
  952.                         zoomDocProc, zoomNoGrow, rDocProc] THEN BEGIN
  953.         GetPort(curGraf);
  954.         GetWMgrPort(wMgrPort);                        {I need to know the font...}
  955.         SetPort(wMgrPort);                            {info in the System’s port}
  956.         GetFontInfo(info);
  957.         SetPort(curGraf);                                {restore current port}
  958.         WITH info DO
  959.             wTitleHeight:= ascent + descent + leading + 2;
  960.         IF wTitleHeight < 19 THEN
  961.             wTitleHeight:= 19;                        {the title is always at least 19}
  962.         GetWTitleHeight:= wTitleHeight;
  963.     END ELSE
  964.         GetWTitleHeight:= 0;                            {other window types have no title}
  965. END; {GetWTitleHeight}
  966.  
  967. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  968. {$S Main}
  969. FUNCTION GetGlobalTopLeft(window: WindowPtr): Point;
  970.  
  971. {Given a window, this will return the top left point of the window’s
  972.  port in global coordinates.  Something this doesn’t include, is the
  973.  window’s drag region (or title bar).  This returns the top left point
  974.  of the window’s content area only.
  975.  
  976.  In this routine, I violate my rule about not using the GetPort, SetPort,
  977.  SetPort sequence mentioned at the start of the file. Mostly, I do this
  978.  because it’s not all that apparent that a routine called GetGlobalTopLeft
  979.  will change the port, so I make sure that it doesn’t.}
  980.  
  981. VAR
  982.     theGraf:            GrafPtr;
  983.     globalPt:        Point;
  984.  
  985. BEGIN
  986.     GetPort(theGraf);
  987.     SetPort(window);
  988.     globalPt:= window^.portRect.topLeft;
  989.     LocalToGlobal(globalPt);
  990.     SetPort(theGraf);
  991.     GetGlobalTopLeft:= globalPt;
  992. END; {GetGlobalTopLeft}
  993.  
  994. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  995. {$S Main}
  996. PROCEDURE MyParamText(text: StringHandle; cite0, cite1: StringPtr);
  997.  
  998. {I’m using string pointers (not necessarily Memory Manager pointers)
  999.  to the replacement strings.  Using Str255 would copy the string to the
  1000.  stack, and then to the text handle.  This way it is only copied once.}
  1001.  
  1002. VAR
  1003.     offSet:            LONGINT;
  1004.     param0,
  1005.     param1:            PACKED ARRAY [1..2] OF CHAR;
  1006.     newLength:        LONGINT;
  1007.  
  1008. BEGIN
  1009.     param0:= '^0';
  1010.     param1:= '^1';
  1011.     IF cite0^ <> '' THEN
  1012.         offSet:= Munger(Handle(text), 1, @param0, SIZEOF(param0),
  1013.                              Ptr(ORD4(cite0) + 1), LENGTH(cite0^));
  1014.     IF cite1^ <> '' THEN
  1015.         offSet:= Munger(Handle(text), 1, @param1, SIZEOF(param1),
  1016.                              Ptr(ORD4(cite1) + 1), LENGTH(cite1^));
  1017.     newLength:= GetHandleSize(Handle(text)) - 1;
  1018.     IF newLength > 255 THEN
  1019.         newLength:= 255;
  1020.     text^^[0]:= CHAR(newLength);                        {string’s new length byte}
  1021. END;
  1022.  
  1023. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1024. {$S Open}
  1025. PROCEDURE CenterWindowRect(variant: INTEGER; VAR theRect: Rect);
  1026.  
  1027. {Given a window’s portRect, this routine will center the rectangle on the
  1028.  main device within the desktop region.  This excludes the menu bar area.
  1029.  It follows the Apple Human Interface Guidelines for where to place a
  1030.  window centered on the screen. That is, 1/3th of the desktop shows above
  1031.  the window and 2/3ths below it.  It returns a new rectangle set to the
  1032.  centered position.  The top and left of this rectangle can be used with
  1033.  MoveWindow.  This routine only considers the main device.  CenterWindowRect
  1034.  could take a GDevice as a parameter to center the VAR rect with.  This
  1035.  would also allow Alerts or dialogs that are closely associated with a
  1036.  document window to be centered relative to the monitor that contains that
  1037.  document.  This is also one of the Human Interface Guidelines.  MacApp 2.0
  1038.  has a utility CalcScreenRect that you can borrow from to include this.
  1039.  
  1040.  WARNING: This routine may move or purge memory.}
  1041.  
  1042. VAR
  1043.     rectSize:         Point;
  1044.     wTitleHeight:    INTEGER;
  1045.  
  1046. BEGIN
  1047.     wTitleHeight:= GetWTitleHeight(variant);                {get title height}
  1048.     WITH theRect DO BEGIN                                        {get size of rect}
  1049.         SetPt(rectSize, right, bottom + wTitleHeight);    {include it in size}
  1050.         SubPt(topLeft, rectSize);
  1051.     END;
  1052.     WITH screenBits.bounds DO BEGIN                            {1/3th below menubar}
  1053.         theRect.top:= ((bottom - top - GetMBarHeight - rectSize.v) DIV 3)
  1054.                           + GetMBarHeight;
  1055.         theRect.left:= ((right - left) - rectSize.h) DIV 2;    {centered horz}
  1056.     END;
  1057.     WITH theRect DO BEGIN                                        {return adjusted rect}
  1058.         SetPt(botRight, left, top);
  1059.         AddPt(rectSize, botRight);
  1060.         top:= top + wTitleHeight;                    {remove title height from rect}
  1061.     END;
  1062. END; {CenterWindowRect}
  1063.  
  1064. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1065. {$S Open}
  1066. FUNCTION GetCenteredWindow(id: INTEGER; p: Ptr; behind: WindowPtr): WindowPtr;
  1067.  
  1068. {Given a window ID, this routine will center the window’s rectangle before
  1069.  showing it on the main screen.  This follows the Apple Human Interface
  1070.  Guidelines for where to place a centered window on the screen.  If the
  1071.  window is closely associated with another window, considerations should be
  1072.  given to where that other window is located.  If this other window is on a
  1073.  screen other then the main monitor, then it would be best to center the
  1074.  window on that other monitor.}
  1075.  
  1076. VAR
  1077.     newRect:            Rect;
  1078.     windTemplate:    WindowTHndl;
  1079.     window:            WindowPtr;
  1080.  
  1081. BEGIN
  1082.     window:= NIL;                                                {initialize result}
  1083.     windTemplate:= WindowTHndl(Get1Resource('WIND', id));
  1084.     IF windTemplate <> NIL THEN BEGIN
  1085.         HNoPurge(Handle(windTemplate));
  1086.         newRect:= windTemplate^^.boundsRect;
  1087.         CenterWindowRect(windTemplate^^.procID, newRect);
  1088.         windTemplate^^.boundsRect:= newRect;
  1089.         window:= GetNewWindow(id, p, behind);
  1090.         HPurge(Handle(windTemplate));
  1091.     END;
  1092.     GetCenteredWindow:= window;
  1093. END;
  1094.  
  1095. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1096. {$S Open}
  1097. FUNCTION CenteredAlert(alertID: INTEGER): INTEGER;
  1098.  
  1099. {Given an Alert ID, this routine will center the alert’s rectangle before
  1100.  showing it on the main screen.  This follows the Apple Human Interface
  1101.  Guidelines for where to place a centered window on the screen.  If the
  1102.  Alert is closely associated with another window, considerations should be
  1103.  given to what the window is located.  If this other window is on a screen
  1104.  other then the main monitor, then it would be best to center the Alert on
  1105.  that other monitor.}
  1106.  
  1107. VAR
  1108.     alertHandle:    AlertTHndl;
  1109.     alertRect:        Rect;
  1110.     itemHit:            INTEGER;
  1111.  
  1112. BEGIN
  1113.     alertHandle:= AlertTHndl(Get1Resource('ALRT', alertID));
  1114.     IF alertHandle <> NIL THEN BEGIN
  1115.         HNoPurge(Handle(alertHandle));
  1116.         alertRect:= alertHandle^^.boundsRect;
  1117.         CenterWindowRect(dBoxProc, alertRect);
  1118.         alertHandle^^.boundsRect:= alertRect;
  1119.         HPurge(Handle(alertHandle));
  1120.     END;
  1121.     CenteredAlert:= Alert(alertID, NIL);
  1122. END; {CenteredAlert}
  1123.  
  1124. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1125. {$S Open}
  1126. FUNCTION GetCenteredDialog(id: INTEGER; p: Ptr; behind: WindowPtr): DialogPtr;
  1127.  
  1128. {Given a dialog ID, this routine will center the dialog’s rectangle before
  1129.  showing it on the main screen.  This follows the Apple Human Interface
  1130.  Guidelines for where to place a centered window on the screen.  If the
  1131.  dialog is closely associated with another window, considerations should be
  1132.  given to what the window is located.  If this other window is on a screen
  1133.  other then the main monitor, then it would be best to center the dialog on
  1134.  that other monitor.}
  1135.  
  1136. VAR
  1137.     newRect:            Rect;
  1138.     dlogTemplate:    DialogTHndl;
  1139.     dialog:            DialogPtr;
  1140.  
  1141. BEGIN
  1142.     dialog:= NIL;                                                {initialize result}
  1143.     dlogTemplate:= DialogTHndl(Get1Resource('DLOG', id));
  1144.     IF dlogTemplate <> NIL THEN BEGIN
  1145.         newRect:= dlogTemplate^^.boundsRect;
  1146.         CenterWindowRect(dlogTemplate^^.procID, newRect);
  1147.         dlogTemplate^^.boundsRect:= newRect;
  1148.         HNoPurge(Handle(dlogTemplate));
  1149.         dialog:= GetNewDialog(id, p, behind);
  1150.         HPurge(Handle(dlogTemplate));
  1151.     END;
  1152.     GetCenteredDialog:= dialog;
  1153. END; {GetCenteredDialog}
  1154.  
  1155. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1156. {$S Main}
  1157. PROCEDURE DoButtonOutline(button: ControlHandle);
  1158.  
  1159. {Given any control handle, this will draw an outline around it.  This is
  1160.  used for the default button of a window.  The extra nice feature here is
  1161.  that I’ll erase the outline for buttons that are inactive.  Seems like
  1162.  there should be a Toolbox call for getting a control’s hilite state.
  1163.  Since there isn’t, I have to look into the control record myself.  This
  1164.  should be called for update and activate events.
  1165.  
  1166.  The method for determining the oval diameters for the roundrect is a
  1167.  little different than that recommended by Inside Mac.  IM I-407 suggests
  1168.  that you use a hardcoded (16,16) for the diameters. However, this only
  1169.  looks good for small roundrects. For larger ones, the outline doesn’t
  1170.  follow the inner roundrect because the CDEF for simply buttons doesn’t
  1171.  use (16,16). Instead, it uses half the height of the button as the
  1172.  diameter. By using this formula, too, our outlines look better.
  1173.  
  1174.  WARNING: This will set the current port to the control’s window.}
  1175.  
  1176. VAR
  1177.     theRect:            Rect;
  1178.     curPen:            PenState;
  1179.     buttonOval:        INTEGER;
  1180.  
  1181. BEGIN
  1182.     IF button <> NIL THEN BEGIN
  1183.         SetPort(button^^.contrlOwner);
  1184.         GetPenState(curPen);
  1185.         PenNormal;
  1186.         theRect:= button^^.contrlRect;
  1187.         InsetRect(theRect, kButtonFrameInset, kButtonFrameInset);
  1188.         buttonOval := (theRect.bottom - theRect.top) DIV 2;
  1189.         IF (button^^.contrlHilite = kCntlActivate) THEN
  1190.             PenPat(black)
  1191.         ELSE
  1192.             PenPat(gray);
  1193.         PenSize(kButtonFrameSize, kButtonFrameSize);
  1194.         FrameRoundRect(theRect, buttonOval, buttonOval);
  1195.         SetPenState(curPen);
  1196.     END;
  1197. END;
  1198.  
  1199. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1200. {$S Main}
  1201. PROCEDURE SelectButton(button: ControlHandle);
  1202.  
  1203. {Given the button control handle, this will cause the button to look as
  1204.  if it has been clicked in.  This is nice to do for the user if they type
  1205.  return or enter to select the default item.}
  1206.  
  1207. VAR
  1208.     finalTicks:        LONGINT;
  1209.  
  1210. BEGIN
  1211.     HiliteControl(button, kSelect);
  1212.     Delay(kDelayTime, finalTicks);
  1213.     HiliteControl(button, kDeselect);
  1214. END; {SelectButton}
  1215.  
  1216. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1217. {$S Main}
  1218. FUNCTION IsDAWindow(window: WindowPtr): BOOLEAN;
  1219.  
  1220. {Check if a window belongs to a desk accessory.  This will first test for a
  1221.  NIL window.  DAs will have a negitive windowKind.}
  1222.  
  1223. BEGIN
  1224.     IF window = NIL THEN
  1225.         IsDAWindow:= FALSE
  1226.     ELSE    {DA windows have negative windowKinds}
  1227.         IsDAWindow:= WindowPeek(window)^.windowKind < 0;
  1228. END; {IsDAWindow}
  1229.  
  1230. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1231. {$S Main}
  1232. FUNCTION IsDocWindow(window: WindowPtr): BOOLEAN;
  1233.  
  1234. {Check to see if a window is a document window.  This will first test for a
  1235.  NIL window.  Document windows all have a refCon set to rSoundWindow.  This
  1236.  insures there is document type information after the window record.}
  1237.  
  1238. BEGIN
  1239.     IF window = NIL THEN
  1240.         IsDocWindow:= FALSE
  1241.     ELSE
  1242.         IsDocWindow:= GetWRefCon(window) = rSoundWindow;
  1243. END; {IsDocWindow}
  1244.  
  1245. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1246. {$S Main}
  1247. FUNCTION IsModalWindow(window: WindowPtr): BOOLEAN;
  1248.  
  1249. {This test will return TRUE for a window that needs to be treated as a
  1250.  modal window.  To include additional windows, add the window’s refCon
  1251.  value to the set of modal windows.}
  1252.  
  1253. VAR
  1254.     wRef:                LONGINT;
  1255.  
  1256. BEGIN
  1257.     IF window = NIL THEN
  1258.         IsModalWindow:= FALSE
  1259.     ELSE BEGIN
  1260.         wRef:= GetWRefCon(window);
  1261.         IsModalWindow:= wRef IN [rAboutWindow];        {set of modal windows}
  1262.     END;
  1263. END;
  1264.  
  1265. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1266. {$S Main}
  1267. PROCEDURE KillSound;
  1268.  
  1269. {This is used to free up all the sound data and channels in use.  There are
  1270.  two reasons for using this routine.  One is after a sound has completed
  1271.  the other is to terminate a sound that may be in progress.  For this
  1272.  second reason, this routine should always be used before playing a new
  1273.  sound.  When disposing of a sound channel, this sets all document’s
  1274.  sndInUse flags to FALSE.  I can call this routine at any time.  When I
  1275.  find that the memory reserve is used, I will call this to free up any
  1276.  possible sound resources which tend to be large.  Another important point
  1277.  is the human interface issue of hiding the status window.  It’s possible
  1278.  that  playing some short sounds could cause the status window to disappear
  1279.  before the user had much of a chance to see it.  To solve this, there is a
  1280.  delay that insures the status window was visible for a minimal time.}
  1281.  
  1282. VAR
  1283.     window:            WindowPtr;
  1284.  
  1285. BEGIN
  1286.     IF SndChanOpen THEN BEGIN                                {if a channel is open...}
  1287.         window:= FrontWindow;                                {set all document’s flags}
  1288.         WHILE window <> NIL DO BEGIN
  1289.             IF IsDocWindow(window) THEN                    {if this is my document...}
  1290.                 SndDocPeek(window)^.sndInUse:= FALSE;    {then it is no longer active}
  1291.             window:= WindowPtr(WindowPeek(window)^.nextWindow);
  1292.         END;
  1293.     END;
  1294.     IF SoundCompletion THEN    BEGIN                            {why were we called?}
  1295.         DoSoundComplete;                                        {from completion}
  1296.         REPEAT                                                    {delay for status window}
  1297.         UNTIL (TickCount - gStatusWindow^.showTime) > 20;
  1298.     END ELSE
  1299.         FreeAllChans;                                            {or just because}
  1300.     HideWindow(WindowPtr(gStatusWindow));
  1301. END; {KillSound}
  1302.  
  1303. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1304. {$S Main}
  1305. FUNCTION DoCloseWindow(window: WindowPtr): BOOLEAN;
  1306.  
  1307. {Close any of my windows.  At this point, if there was a document
  1308.  associated with a window, you could do any document saving processing if
  1309.  it has been changed since being opened.  DoCloseWindow would return TRUE
  1310.  if the window actually closed.  FALSE would be returned, as an example, if
  1311.  the user chose “Cancel” in the Save As… dialog.  An important detail is if
  1312.  the window to be close is one of my documents that is currently playing a
  1313.  sound.  We cannot dispose of it yet, since the sound resource owned by the
  1314.  document would be in use by the Sound Manager.  So, I test the document’s
  1315.  sndInUse flag and if it is in use I call KillSound.  The About window
  1316.  contains some resource handles.  I only mark them purgeable, but I could
  1317.  use ReleaseResource and then DisposHandle.}
  1318.  
  1319. BEGIN
  1320.     DoCloseWindow:= TRUE;
  1321.     CASE GetWRefCon(window) OF
  1322.  
  1323.         rSoundWindow: BEGIN
  1324.             IF SndDocPeek(window)^.sndInUse THEN        {contain a snd in use?}
  1325.                 KillSound;                                        {not any more}
  1326.             IF SndDocPeek(window)^.list <> NIL THEN    {dispose of document data}
  1327.                 LDispose(SndDocPeek(window)^.list);
  1328.             IF SndDocPeek(window)^.resFile <> 0 THEN
  1329.                 CloseResFile(SndDocPeek(window)^.resFile);
  1330.             KillControls(window);
  1331.             CloseWindow(WindowPtr(window));
  1332.             DisposPtr(Ptr(window));                            {dispose of our doc storage}
  1333.         END;
  1334.  
  1335.         rStatusWindow: BEGIN
  1336.             KillControls(WindowPtr(gStatusWindow));
  1337.             DisposHandle(Handle(gStatusWindow^.message));
  1338.             CloseWindow(WindowPtr(gStatusWindow));
  1339.             DisposPtr(Ptr(gStatusWindow));
  1340.         END;
  1341.  
  1342.         rAboutWindow: BEGIN
  1343.             IF AboutWPeek(window)^.comment <> NIL THEN        {never dispose...}
  1344.                 HPurge(AboutWPeek(window)^.comment);            {a Resource handle}
  1345.             IF AboutWPeek(window)^.appPict <> NIL THEN
  1346.                 HPurge(AboutWPeek(window)^.appPict);
  1347.             IF AboutWPeek(window)^.appIcon <> NIL THEN
  1348.                 IF AboutWPeek(window)^.iconIsColor THEN
  1349.                     DisposCIcon(CIconHandle(AboutWPeek(window)^.appIcon))
  1350.                 ELSE
  1351.                     HPurge(AboutWPeek(window)^.appIcon);         {disposCIcon}
  1352.             KillControls(window);
  1353.             CloseWindow(WindowPtr(window));
  1354.             DisposPtr(Ptr(window));
  1355.         END;
  1356.  
  1357.         OTHERWISE
  1358.             IF IsDAWindow(window) THEN                        {we can close DAs too}
  1359.                 CloseDeskAcc(WindowPeek(window)^.windowKind);
  1360.  
  1361.     END; {CASE GetWRefCon(window)}
  1362. END; {DoCloseWindow}
  1363.  
  1364. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1365. {$S Main}
  1366. PROCEDURE AlertUser(error: INTEGER; messageID: INTEGER);
  1367.  
  1368. {Display an alert to inform the user of an error.  MessageID acts as an
  1369.  index into a STR# resource of error messages.  This will attempt to
  1370.  replace the error number with a string if the sound is a Sound Manager
  1371.  error.
  1372.  
  1373.  BUG NOTE: GetIndString will return a bogus string if the index is not
  1374.  positive.}
  1375.  
  1376. VAR
  1377.     msg1, msg2:        Str255;
  1378.     theItem:            INTEGER;
  1379.  
  1380. BEGIN
  1381.     UseResFile(gAppResRef);                                {restore our resource file}
  1382.     IF messageID > 0 THEN
  1383.         GetIndString(msg1, sErrStrings, messageID)
  1384.     ELSE
  1385.         msg1:= '';                                            {in case there is no message}
  1386.     IF (error <= noHardware) & (error >= badFormat) THEN
  1387.         GetIndString(msg2, sSMErrStrings, ABS(error) + noHardware + 1)
  1388.     ELSE
  1389.         NumToString(error, msg2);
  1390.     ParamText(msg1, msg2, '', '');
  1391.     theItem:= CenteredAlert(rUserAlert);
  1392. END; {AlertUser}
  1393.  
  1394. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1395. {$S Main}
  1396. PROCEDURE EmergencyExit(message: INTEGER);
  1397.  
  1398. {Display an alert that tells the user an error occurred, then exit the
  1399.  program.  This routine is used as an ultimate bail-out for serious errors
  1400.  that prohibit the continuation of the application.  Errors that do not
  1401.  require the termination of the application are handled with AlertUser.
  1402.  Error checking and reporting has a place even in the simplest application.
  1403.  
  1404.  BUG NOTE: GetIndString will return a bogus string if the index is not
  1405.  positive.}
  1406.  
  1407. VAR
  1408.     msg1:                Str255;
  1409.     theItem:            INTEGER;
  1410.  
  1411. BEGIN
  1412.     SetCursor(arrow);
  1413.     IF message > 0 THEN
  1414.         GetIndString(msg1, sErrStrings, message)
  1415.     ELSE
  1416.         msg1:= '';                                            {in case there is no message}
  1417.     ParamText(msg1, '', '', '');
  1418.     theItem:= CenteredAlert(rExitAlert);
  1419.     ExitToShell;                                            {we’re out of here}
  1420. END; {EmergencyExit}
  1421.  
  1422. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1423. {$S Main}
  1424. PROCEDURE DrawStatusWindow;
  1425.  
  1426. {Draw the status message and update the button.  I setup a rectangle that
  1427.  is the text area.  This is the entire window area, inset a small amount.
  1428.  I also subtract from the bottom of the rectangle the area used by the button.
  1429.  Doing things this way allowed me to change the size of the window and
  1430.  not change any of this code.  The rectangle used by text will fill the
  1431.  window regardless of the new size I give it in the WIND resource.}
  1432.  
  1433. VAR
  1434.     theRect:         Rect;
  1435.  
  1436. BEGIN
  1437.     PenNormal;
  1438.     WITH WindowPtr(gStatusWindow)^.portRect DO
  1439.         SetRect(theRect, left, top, right, bottom - kDafaultButSizeH);
  1440.     InsetRect(theRect, kMsgInset, kMsgInset);
  1441.     HLock(Handle(gStatusWindow^.message));
  1442.     TextBox(Ptr(ORD(gStatusWindow^.message^) + 1),
  1443.                 LENGTH(gStatusWindow^.message^^), theRect, teJustCenter);
  1444.     HUnlock(Handle(gStatusWindow^.message));
  1445.     UpdtControl(WindowPtr(gStatusWindow), WindowPtr(gStatusWindow)^.visRgn);
  1446.     DoButtonOutline(WindowPeek(gStatusWindow)^.ControlList);
  1447. END; {DrawStatusWindow}
  1448.  
  1449. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1450. {$S Main}
  1451. PROCEDURE ShowStatusWindow(messageID: INTEGER);
  1452.  
  1453. {Whenever I start a sound, I show this status window.  It will contain a
  1454.  message showing what is currently happening.  A very good rule is not to
  1455.  perform drawing outside of the update event.  I bend that rule here.  I
  1456.  could simply select this window and show it.  This would allow my normal
  1457.  drawing and activating routines to be called.  The problem with that was,
  1458.  I found that many times the status window appeared and then disappeared
  1459.  before these update routines had a chance to draw the window.  This left
  1460.  the user with a blank window that immediately went away.  So, I do the
  1461.  activation and drawing right after showing it.
  1462.  
  1463.  BUG NOTE: GetIndString will return a bogus string if the index is not
  1464.  positive.}
  1465.  
  1466. VAR
  1467.     msg:                Str255;
  1468.  
  1469. BEGIN
  1470.     IF FailLowMemory(0) THEN BEGIN                            {running low on memory?}
  1471.         KillSound;
  1472.         AlertUser(memFullErr, sLowMemory);
  1473.     END ELSE BEGIN
  1474.         IF messageID > 0 THEN
  1475.             GetIndString(msg, sMsgStrings, messageID)
  1476.         ELSE
  1477.             msg:= '';                                                {case there’s no message}
  1478.         SetString(gStatusWindow^.message, msg);
  1479.         ShowWindow(WindowPtr(gStatusWindow));                {show the window}
  1480.         SelectWindow(WindowPtr(gStatusWindow));            {bring it to the front}
  1481.         SetPort(GrafPtr(gStatusWindow));
  1482.         EraseRect(WindowPtr(gStatusWindow)^.portRect);    {erase the old message}
  1483.         HiliteControl(WindowPeek(gStatusWindow)^.ControlList, kCntlActivate);
  1484.         DrawStatusWindow;                                            {draw the new message}
  1485.         ValidRect(WindowPtr(gStatusWindow)^.portRect);    {avoid a needless update}
  1486.         gStatusWindow^.showTime:= TickCount;                {it’s show time folks}
  1487.     END;
  1488. END; {ShowStatusWindow}
  1489.  
  1490. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1491. {$S Initialize}
  1492. PROCEDURE InitStatusWindow;
  1493.  
  1494. {This initializes the status window, and keeps it hidden until the user
  1495.  decides to play a sound.  I also center it for the first time, but the
  1496.  user is free to drag it to a new location afterwards.  The status window
  1497.  also has a message associated to it, so I allocate a string handle for this.}
  1498.  
  1499. VAR
  1500.     window:            WindowPtr;
  1501.     stopButton:        ControlHandle;
  1502.  
  1503. BEGIN
  1504.     gStatusWindow:= StatWindowPeek(NewPtrClear(SIZEOF(StatusWindow)));
  1505.     IF gStatusWindow = NIL THEN
  1506.         EmergencyExit(sInitStatusErr);
  1507.     window:= GetCenteredWindow(rStatusWindow, Ptr(gStatusWindow), Pointer(-1));
  1508.     IF window = NIL THEN
  1509.         EmergencyExit(sInitStatusErr);
  1510.     SetWRefCon(window, rStatusWindow);
  1511.     stopButton:= GetNewControl(rCancelCntl, window);
  1512.     IF stopButton = NIL THEN
  1513.         EmergencyExit(sInitStatusErr);
  1514.     gStatusWindow^.message:= NewString('');        {a new empty string handle}
  1515.     IF gStatusWindow^.message = NIL THEN
  1516.         EmergencyExit(sInitStatusErr);
  1517.     HNoPurge(Handle(gStatusWindow^.message));
  1518. END; {InitStatusWindow}
  1519.  
  1520. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1521. {$S Main}
  1522. PROCEDURE DoErrorSound(soundNo: INTEGER);
  1523.  
  1524. {I just flash the menubar for a moment instead of playing any sounds.  It’s
  1525.  the same effect as setting the sound volume to zero but that would prevent
  1526.  me playing my sounds.  Also, it helps to prevent the problem of _SysBeep
  1527.  being called by the Dialog Manager while I’m playing a sound.  If my
  1528.  application is playing a sound and, for example, the user clicks outside
  1529.  of the Standard File dialog ModalDialog calls _SysBeep.  This can cause
  1530.  the Mac to crash or trash my channel.
  1531.  
  1532.  BUG NOTE: If the current Sound Manager were playing a sound and a
  1533.  _SysBeep were to occur, bad things could happen on a Mac Plus/SE.  Either
  1534.  the application’s channel would be trashed or the Mac could crash.}
  1535.  
  1536. VAR
  1537.     finalTicks:        LongInt;
  1538.  
  1539. BEGIN
  1540.     IF soundNo > 0 THEN BEGIN                            {only after the first time}
  1541.         FlashMenuBar(0);
  1542.         Delay(kDelayTime, finalTicks);
  1543.         FlashMenuBar(0);
  1544.     END;
  1545. END;
  1546.  
  1547. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1548. {$S Initialize}
  1549. PROCEDURE CheckSndVol;
  1550.  
  1551. {This tests if the volume has been set very low.  It’s a judgement call as
  1552.  to what “too low” means.  The user sets the volume, so how could it be too
  1553.  low? A setting of 0 could be considered too low, but in any case do not
  1554.  adjust it.  I find the volume goes below 4 on a standard Mac, then there
  1555.  is a perceivable difference.  I also wanted to show this routine as a
  1556.  demonstration in how to handle such a situation.  Do not change it
  1557.  directly! Ask the user to do it.  Consider the user that has their Mac
  1558.  connected to a stack of Marshalls (which go to 11) and has purposely set
  1559.  their Mac’s volume where they wanted it.  This may be 3 and if you crack
  1560.  it up to 8, it could be a scene out of Back to the Future.
  1561.  
  1562.  User Interface rule, let the user remain in control!}
  1563.  
  1564. VAR
  1565.     curVol,
  1566.     item:            INTEGER;
  1567.     numStr:        Str255;
  1568.  
  1569. BEGIN
  1570.     GetSoundVol(curVol);
  1571.     IF (curVol < kMinVolumeDesired) THEN BEGIN
  1572.         NumToString(curVol, numStr);
  1573.         ParamText(numStr, '', '', '');                    {show the current volume}
  1574.         item:= CenteredAlert(rSoundVolAlert);
  1575.     END;
  1576. END;
  1577.  
  1578. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1579. {$S Initialize}
  1580. PROCEDURE Initialize;
  1581.  
  1582. {Set up the whole world.  Initialize global variables, Toolbox managers,
  1583.  and menus.  If a failure occurs here, I will consider that the application
  1584.  is in such bad shape that I should just exit.  Your error handling may
  1585.  differ, but the checks should still be made.  I ask for a set of master
  1586.  pointer blocks and all permanent storage at this point to cut down on
  1587.  memory fragmentation.  I may be opening large numbers of resources and
  1588.  documents so I allocate some extra master pointer blocks at the start.}
  1589.  
  1590. CONST
  1591.     kBroughtToFront =    3;
  1592.  
  1593. VAR
  1594.     event:                 EventRecord;
  1595.     menuBar:             Handle;
  1596.     total, contig:        LONGINT;
  1597.     count:                 INTEGER;
  1598.     ignoreError:        OSErr;
  1599.     ignoreResult:         BOOLEAN;
  1600.  
  1601. BEGIN
  1602.     gInBackground:= FALSE;                        {we’ll be in the foreground soon}
  1603.     gAppResRef:= CurResFile;                    {save the resRef to myself}
  1604.     FOR count:= 1 TO kNumberOfMasters DO    {allocate master pointer blocks}
  1605.         MoreMasters;
  1606.     InitGraf(@thePort);                            {init managers, yawn...}
  1607.     InitFonts;
  1608.     InitWindows;
  1609.     InitMenus;
  1610.     TEInit;
  1611.     InitDialogs(NIL);
  1612.     InitCursor;
  1613.  
  1614. {This next line prevents the Dialog Manager from calling _SysBeep.
  1615.  If I get a memory or resource Manager error it wouldn’t be the best
  1616.  of plans to call  _SysBeep which will want to allocate memory and load
  1617.  a few resources.  Which could be bad if I just gave an Alert signalling
  1618.  an out of memory condition.}
  1619.  
  1620.     ErrorSound(@DoErrorSound);
  1621.  
  1622. {This code is necessary to pull the application into the foreground.  I use
  1623.  EventAvail because I don’t want to remove any events the user may have
  1624.  done, such as typing ahead.  Until the application has made a few calls (3
  1625.  seems to be the magic number) to the Event Manager, MultiFinder keeps me
  1626.  in the background.   Splashscreens and Alerts will remain in a background
  1627.  layer until we get a few events.  This is documented in Tech Note #180.}
  1628.  
  1629.     FOR count:= 1 TO kBroughtToFront DO
  1630.         ignoreResult:= EventAvail(everyEvent, event);
  1631.  
  1632. {Ignore the error returned from SysEnvirons; even if an error occurred,
  1633.  the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  1634.  call to SysEnvirons by calling it after initializing AppleTalk.}
  1635.  
  1636.     ignoreError:= SysEnvirons(kSysEnvironsVersion, gMac);
  1637.  
  1638. {Make sure we’re running the right system.  If the Sound Manager is not
  1639.  available, then there’s no point in continuing.}
  1640.  
  1641.     IF gMac.systemVersion < kSystem602 THEN
  1642.         EmergencyExit(sWrongVersion);
  1643.  
  1644. {Before I go any further, I want my reserve memory.  This is an emergency
  1645.  reserve (sorta like my old VW had) when memory runs low.  If I cannot
  1646.  obtain this reserve, then I’ll bail.  It’s also important to obtain my
  1647.  reserve before testing if I have the desired amount of memory to run
  1648.  this application.  Also, FailLowMemory will consider the memory reserve.}
  1649.  
  1650.     IF NOT AllocateReserve THEN
  1651.         EmergencyExit(sLowMemory);
  1652.     SetGrowZone(@MyGrowZone);
  1653.  
  1654.     menuBar:= GetNewMBar(rMenuBar);                {read menus into menu bar}
  1655.     IF menuBar = NIL THEN
  1656.         EmergencyExit(sNoMenus);                    {wow, how’d that happen?}
  1657.     SetMenuBar(menuBar);                                {install menus}
  1658.     DisposHandle(menuBar);
  1659.     AddResMenu(GetMHandle(mApple), 'DRVR');    {add DA names to Apple menu}
  1660.     DrawMenuBar;
  1661.  
  1662. {Call the SoundUnit to initialize itslef.  If the unit encounters an error,
  1663.  then it cannot be used and this means I’m leaving too.}
  1664.  
  1665.     IF InitSoundUnit <> noErr THEN                {allocates 4 * 1064 bytes}
  1666.         EmergencyExit(sInitSoundErr);
  1667.     InitStatusWindow;                                    {get the status window ready}
  1668.     InitCursorCtl(NIL);                                {MPW’s handy cursor routines}
  1669.  
  1670. {Last, I want to make sure that enough memory is free for my application to
  1671.  run.  It is possible that user may have adjusted the SIZE resource to too
  1672.  small a setting or for some other reason the application started up in a
  1673.  very small memory partition.  It’s also possible for a situation to arise
  1674.  where the heap may have been of the requested size taken from the SIZE
  1675.  resource, but a large scrap was loaded which left too little memory.  I
  1676.  want to make sure that my free memory is not being modified by the scrap’s
  1677.  presence.  So, I unload it to disk but if the application will run once
  1678.  the scrap is unloaded, then you’ll probably not get it back into memory.
  1679.  Thus losing the clipboard contents.  I preform this check after
  1680.  initializing all the Toolbox and the basic features of this application,
  1681.  such as showing the about box.}
  1682.  
  1683.     IF FailLowMemory(kMinSpace) THEN BEGIN        {I don’t use the scrap, so...}
  1684.         IF UnloadScrap <> noErr THEN
  1685.             EmergencyExit(sLowMemory)
  1686.         ELSE BEGIN
  1687.             IF FailLowMemory(kMinSpace) THEN
  1688.                 EmergencyExit(sLowMemory);
  1689.         END;
  1690.     END;
  1691.  
  1692. {I check the sound volume after testing for a minimal amount of memory to
  1693.  run.  Otherwise I might end up telling the user to adjust the volume and
  1694.  the quitting because memory was too low.}
  1695.  
  1696.     CheckSndVol;                                        {check the sound volume level}
  1697. END; {Initialize}
  1698.  
  1699. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1700. {$S Main}
  1701. PROCEDURE Terminate;
  1702.  
  1703. {Clean up the application and exit.  I close all of the windows so that
  1704.  they can update their documents, if any.  Dispose of the Sound Unit and
  1705.  close the status window if the user really wants to quit.}
  1706.  
  1707. VAR
  1708.     aWindow:        WindowPtr;
  1709.     closed:        BOOLEAN;
  1710.  
  1711. BEGIN
  1712.     closed:= TRUE;
  1713.     KillSound;                                            {stop any sound in progress}
  1714.     REPEAT
  1715.         aWindow:= FrontWindow;                        {get the current front window}
  1716.         IF aWindow <> NIL THEN
  1717.             closed:= DoCloseWindow(aWindow);        {close this window}
  1718.     UNTIL (NOT closed) | (aWindow = NIL);        {do all windows}
  1719.     IF closed THEN BEGIN
  1720.         FreeSoundUnit;                                    {get rid of all sound equipment}
  1721.         ExitToShell;                                    {exit if no cancellation}
  1722.     END;
  1723. END; {Terminate}
  1724.  
  1725. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1726. {$S Open}
  1727. PROCEDURE AddSndDocControls(window: WindowPtr);
  1728.  
  1729. {Simply add all the buttons I want to use in the document window.  I get
  1730.  the control templates, and add the control to the window.  I don’t check
  1731.  for getting errors for two reasons.  I put these controls there.  If the
  1732.  user removes them, it’s their problem.  If the application cannot get the
  1733.  memory required for these, then the application is already out of memory
  1734.  and checking here probably wouldn’t help much.  I do check before creating
  1735.  the document that there was enough available memory.  I save the resource
  1736.  ID into the control’s refCon so later I can tell which control was hit by
  1737.  the user.}
  1738.  
  1739. VAR
  1740.     control:                    ControlHandle;
  1741.  
  1742. BEGIN
  1743.     control:= GetNewControl(rPlaySndCntl, window);
  1744.     IF control <> NIL THEN
  1745.         SetCRefCon(control, rPlaySndCntl);
  1746.     control:= GetNewControl(rHyperPlayCntl, window);
  1747.     IF control <> NIL THEN
  1748.         SetCRefCon(control, rHyperPlayCntl);
  1749.     control:= GetNewControl(rPlayScaleCntl, window);
  1750.     IF control <> NIL THEN
  1751.         SetCRefCon(control, rPlayScaleCntl);
  1752.     control:= GetNewControl(rMelodyCntl, window);
  1753.     IF control <> NIL THEN
  1754.         SetCRefCon(control, rMelodyCntl);
  1755.     control:= GetNewControl(rStopCntl, window);
  1756.     IF control <> NIL THEN
  1757.         SetCRefCon(control, rStopCntl);
  1758. END;
  1759.  
  1760. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1761. {$S Open}
  1762. FUNCTION InitSndList(docPtr: SndDocPeek): OSErr;
  1763.  
  1764. {This is used to create the list showing all the snd resources in the file.
  1765.  If anything goes wrong while attempting to get any of the resources, then I
  1766.  return false.  I don’t want the document to continue if something goes
  1767.  wrong while reading a resource.  If I do get the resource, then I add its
  1768.  name to the list in a new row.  I’m assured that at least one resource is
  1769.  in the file before this routine is called.  Untitled resources will get one.}
  1770.  
  1771. VAR
  1772.     index, resID,
  1773.     newRow, numSnd:    INTEGER;
  1774.     resHandle:            Handle;
  1775.     strHandle:            StringHandle;
  1776.     itsType:                ResType;
  1777.     resName, untitled:Str255;
  1778.     aCell:                Point;
  1779.  
  1780. BEGIN
  1781.     InitSndList:= noErr;
  1782.     strHandle:= StringHandle(Get1Resource('STR ', rUntitled));
  1783.     IF strHandle <> NIL THEN
  1784.         untitled:= strHandle^^                    {save no name title}
  1785.     ELSE
  1786.         untitled:= '';                                {at least an empty string}
  1787.     UseResFile(docPtr^.resFile);
  1788.     numSnd:= Count1Resources('snd ');
  1789.     newRow:= LAddRow(numSnd, 0, docPtr^.list);
  1790.     FOR index:= 1 TO numSnd DO BEGIN
  1791.         SetResLoad(FALSE);                        {don’t load any resources}
  1792.         resHandle:= Get1IndResource('snd ', index); {only get snd from file}
  1793.         SetResLoad(TRUE);                            {back to normal resource operations}
  1794.         IF resHandle <> NIL THEN BEGIN        {only if I got the snd}
  1795.             GetResInfo(resHandle, resID, itsType, resName);
  1796.             IF resName = '' THEN                    {if the snd isn’t named...}
  1797.                 resName:= untitled;                {give it a name}
  1798.             SetPt(aCell, 0, index - 1);
  1799.             LSetCell(Ptr(ORD(@resName) + 1), LENGTH(resName), aCell, docPtr^.list);
  1800.         END ELSE BEGIN {resHandle = NIL}
  1801.             InitSndList:= resNotFound;            {problem with resource file}
  1802.             index:= numSnd + 1;                    {get out of the loop}
  1803.         END;
  1804.     END;
  1805.     UseResFile(gAppResRef);                        {restore our resource file}
  1806. END;
  1807.  
  1808. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1809. {$S Open}
  1810. FUNCTION NewStackedWindow(windID: INTEGER; windStorage: Ptr): WindowPtr;
  1811.  
  1812. {There are a few approaches I thought of and tried, none of which satisfied
  1813.  me.  ResEdit uses the simplest method, an offset from the front window.  I
  1814.  don’t like this because it may cover up existing windows.  So my approach is
  1815.  to go through the window list looking for an empty spot.  If the empty
  1816.  spot causes the window to go off the screen, then I start a new stack off
  1817.  to the right.  This will cause a new series of window to be stacked.  If the
  1818.  new stack would cause the window to go off screen, then it’s time to give up.
  1819.  All new windows will then be moved to the starting point and there is no
  1820.  further stacking.  If I look at this routine too much, I get real tired.
  1821.  If I try to change it at all, I get woozy trying to make it work again.}
  1822.  
  1823. CONST
  1824.     kStartPt =            2;            {offset from the topLeft of the screen}
  1825.     kStaggerH =            16;        {staggering amounts for new windows}
  1826.     kStaggerV =            3;            {not including the window’s title height}
  1827.  
  1828. VAR
  1829.     windSize, newPt,
  1830.     oldPt, delta:        Point;
  1831.     newWindow,
  1832.     oldWindow:            WindowPtr;
  1833.     wTitleHeight,
  1834.     numStacks:            INTEGER;
  1835.     taken:                BOOLEAN;
  1836.  
  1837.     FUNCTION PositionAvailable: BOOLEAN;
  1838.     BEGIN
  1839.         taken:= FALSE;
  1840.         oldWindow:= FrontWindow;
  1841.         WHILE (oldWindow <> NIL) & NOT taken DO BEGIN
  1842.             IF IsDocWindow(oldWindow) & WindowPeek(oldWindow)^.visible THEN BEGIN
  1843.                 oldPt:= GetGlobalTopLeft(oldWindow);
  1844.                 delta.v:= ABS(newPt.v - oldPt.v);
  1845.                 delta.h:= ABS(newPt.h - oldPt.h);
  1846.                 taken:= (delta.h + delta.v)
  1847.                           <= ((kStaggerH + kStaggerV + wTitleHeight) DIV 2);
  1848.             END;
  1849.             oldWindow:= WindowPtr(WindowPeek(oldWindow)^.nextWindow);
  1850.         END;
  1851.         PositionAvailable:= NOT taken;
  1852.     END;
  1853.  
  1854.     FUNCTION OutOfBounds: BOOLEAN;
  1855.     BEGIN
  1856.         OutOfBounds:= ((newPt.v + windSize.v) > screenBits.bounds.bottom)
  1857.                          | ((newPt.h + windSize.h) > screenBits.bounds.right);
  1858.     END;
  1859.  
  1860. BEGIN {set the initail starting point for a window, less the staggering amount}
  1861.     newWindow:= GetNewWindow(windID, windStorage, WindowPtr(-1));
  1862.     windSize:= newWindow^.portRect.botRight;
  1863.     SubPt(newWindow^.portRect.topLeft, windSize);
  1864.     wTitleHeight:= GetWTitleHeight(GetWVariant(newWindow));
  1865.     SetPt(newPt, kStartPt - kStaggerH, kStartPt - kStaggerV + GetMBarHeight);
  1866.  
  1867.     REPEAT {add the staggering amount then test if the window goes off the screen}
  1868.         taken:= TRUE;
  1869.         SetPt(newPt, newPt.h + kStaggerH, newPt.v + kStaggerV + wTitleHeight);
  1870.         IF OutOfBounds THEN BEGIN
  1871.              numStacks:= numStacks + 1;
  1872.             SetPt(newPt, kStartPt + (numStacks * kStaggerH),
  1873.                               kStartPt + wTitleHeight + GetMBarHeight);
  1874.             IF OutOfBounds THEN BEGIN
  1875.                 SetPt(newPt, kStartPt, kStartPt + wTitleHeight + GetMBarHeight);
  1876.                 taken:= FALSE;
  1877.             END;
  1878.         END;
  1879.     UNTIL NOT taken | PositionAvailable;
  1880.  
  1881.     MoveWindow(newWindow, newPt.h, newPt.v, TRUE);
  1882.     NewStackedWindow:= newWindow;
  1883. END; {NewStackedWindow}
  1884.  
  1885. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1886. {$S Open}
  1887. FUNCTION NewSoundDoc(resRef: INTEGER; fNamePtr: StringPtr;
  1888.                             vRefNum: INTEGER; dirID: LONGINT): OSErr;
  1889.  
  1890. {Create a new sound document and initialize all the data associated with
  1891.  it.  If I encounter an error, then dispose of any memory allocated in the
  1892.  attempt.  Allocate all necessary memory required for a sound document.  I
  1893.  like to use NewPtrClear because is will initialize all the memory.  I
  1894.  depend on real values or zero in my document fields.  Then its time to
  1895.  build a sound document which contains all the controls and the list of
  1896.  sounds.  I get the position for the list kept in a rectangle resource.
  1897.  This  helps me to adjust the size of the list without changing code.  I
  1898.  will make  an additional adjustment to the list’s height to insure better
  1899.  scrolling.  This avoids the ugly white space of an improperly sized
  1900.  rectangle.  If I  cannot create the list, I’ll close the window and return
  1901.  a NIL.  If I find  after creating a new document that I’m low on memory,
  1902.  I’ll close it and  return an error.
  1903.  
  1904.  SPECIAL NOTE: The Human Interface Group suggested that the buttons and the
  1905.  list should in the System font.  I designed these windows using the
  1906.  application font in 10 point.  If you change the call to TextFont, you
  1907.  find that the buttons and the list will work properly in your font choice.}
  1908.  
  1909. VAR
  1910.     newDocPtr:                SndDocPeek;
  1911.     window:                    WindowPtr;
  1912.     list:                        ListHandle;
  1913.     rHandle:                    RectHandle;
  1914.     lView, lBounds:        Rect;
  1915.     aCell:                    Cell;
  1916.     cSize, newSize:        Point;
  1917.     theErr:                    OSErr;
  1918.     ignore:                    BOOLEAN;
  1919.  
  1920. BEGIN
  1921.     newDocPtr:= SndDocPeek(NewPtrClear(SIZEOF(SndDocument)));
  1922.     theErr:= MemError;
  1923.     IF newDocPtr <> NIL THEN BEGIN
  1924.         window:= NewStackedWindow(rSoundWindow, Ptr(newDocPtr));
  1925.         SetPort(window);
  1926.         TextFont(0);                                        {set window to System font, blech}
  1927.         AddSndDocControls(window);                        {add my buttons}
  1928.         SetWRefCon(WindowPtr(newDocPtr), rSoundWindow); {mark as an app window}
  1929.         SetWTitle(WindowPtr(newDocPtr), fNamePtr^);
  1930.         newDocPtr^.resFile:= resRef;                    {save its resource file ref}
  1931.         newDocPtr^.vRefNum:= vRefNum;                    {save its volume reference}
  1932.         newDocPtr^.dirID:= dirID;                        {save its directory ID}
  1933.         newDocPtr^.sndInUse:= FALSE;                    {not yet is doesn’t}
  1934.         rHandle:= RectHandle(Get1Resource('RECT', rListRectID));
  1935.         IF rHandle <> NIL THEN                            {get the stored list size}
  1936.             lView:= rHandle^^;
  1937.         SetRect(lBounds, 0, 0, 1, 0);                    {one dimentional list}
  1938.         SetPt(cSize, 0, 0);                                {List Mgr will find cell size}
  1939.         list:= LNew(lView, lBounds, cSize, 0, window, FALSE, FALSE, FALSE, TRUE);
  1940.         IF list <> NIL THEN BEGIN
  1941.             newSize:= list^^.cellSize;                    {get the size of one cell}
  1942.             WHILE (newSize.v + list^^.cellSize.v) < (lView.bottom - lView.top) DO
  1943.                 newSize.v:= newSize.v + list^^.cellSize.v;
  1944.             LSize(newSize.h, newSize.v, list);        {adjust for best scrolling}
  1945.             list^^.selFlags:= lOnlyOne;                {single selections only}
  1946.             newDocPtr^.list:= list;                        {save the list handle}
  1947.             theErr:= InitSndList(newDocPtr);            {initialize the list data}
  1948.             IF theErr = noErr THEN BEGIN
  1949.                 SetPt(aCell, 0, 0);                        {by default, I will...}
  1950.                 LSetSelect(TRUE, aCell, newDocPtr^.list); {select first item}
  1951.                 LDoDraw(TRUE, newDocPtr^.list);
  1952.                 ShowWindow(WindowPtr(newDocPtr));    {get the show on the road}
  1953.                 IF FailLowMemory(0) THEN                {if I’m low on memory...}
  1954.                     theErr:= memFullErr;
  1955.             END;
  1956.         END ELSE
  1957.             theErr:= nilHandleErr;                        {list handle was NIL}
  1958.         IF theErr <> noErr THEN BEGIN                    {could not create the list}
  1959.             ignore:= DoCloseWindow(window);            {if not, close the window}
  1960.             newDocPtr:= NIL;                                {return NIL pointer too}
  1961.         END;
  1962.     END;
  1963.     NewSoundDoc:= theErr;                                {return the error, if any}
  1964. END; {NewSoundDoc}
  1965.  
  1966. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1967. {$S Open}
  1968. FUNCTION SFFilter(p: ParmBlkPtr): BOOLEAN;
  1969.  
  1970. {This is much more than what a typical file filter might do but I wanted
  1971.  the user to easily find files that contained snd resources.  So, the
  1972.  global flag gSndFilesOnly is used to determine when to filter for such
  1973.  files.  Otherwise, I show all files and allow the application to report to
  1974.  the user the file they’ve just tried to open doesn’t have any sounds to
  1975.  play with.  Opening resource forks can be tricky if it’s already open.  It
  1976.  would be very bad to use a resource fork that is already open by another
  1977.  application.  The problem being that the Resource Manager doesn’t deal
  1978.  with multiple users.  Read Tech notes #116 and #185.  There’s also another
  1979.  problem.  If a resource fork is opened by two applications and one closes
  1980.  the file then the entire resource fork may closed out from underneath the
  1981.  other application.  I do, however, want to show the user files that
  1982.  contain sound resources even if they are currently open.  I use
  1983.  HOpenResFile with read only permission, which will give me a unique
  1984.  resource reference.  I look for a 'snd ' resource and then immediately
  1985.  close the file.  Do not use a resource file opened with read only
  1986.  permission.  Another reason to use HOpenResFile  is to avoid a necessary
  1987.  working directory.  I do not have one while in the file filter, but can
  1988.  use the DirID.  Performing this search on each file is time consuming so I
  1989.  show a spinning cursor to show the user I’m working.   Opening a resource
  1990.  fork may load resources mark preload.   To avoid this, I call SetResLoad
  1991.  to FALSE.  I bet you thought the Resource Manager was a free lunch.  Ha!
  1992.  Read Tech Note #203 for other reasons not to play with resources.
  1993.  
  1994.  BUG NOTE: While debugging this routine using heap scramble, I found that
  1995.  OpenResFile would not open the requested file.  I’m not sure if this is a
  1996.  problem with OpenResFile or SFGetFile.}
  1997.  
  1998. CONST
  1999.     kShowIt =            FALSE;            {FALSE means I do not filter out...}
  2000.     kDoNotShowIt =        TRUE;                {the file and TRUE means that I do.}
  2001.  
  2002. VAR
  2003.     oldTicks:            LONGINT;
  2004.     resRef, curRes:    INTEGER;
  2005.  
  2006. BEGIN
  2007.     oldTicks:= TickCount;
  2008.     IF NOT gSndFilesOnly THEN
  2009.         SFFilter:= kShowIt
  2010.     ELSE BEGIN
  2011.         SFFilter:= kDoNotShowIt;            {don’t show anything until I say so}
  2012.         curRes:= CurResFile;
  2013.         SetResLoad(FALSE);
  2014.         resRef:= HOpenResFile(p^.ioVRefNum, LongIntPtr(CurDirStore)^,
  2015.                                         p^.ioNamePtr^, fsRdPerm);
  2016.         IF (resRef <> -1) THEN BEGIN
  2017.             UseResFile(resRef);
  2018.             IF Count1Resources('snd ') > 0 THEN
  2019.                 SFFilter:= kShowIt;            {hey, we found a sound in here}
  2020.             CloseResFile(resRef);
  2021.         END;                                        {restore everything}
  2022.         SetResLoad(TRUE);
  2023.         UseResFile(curRes);
  2024.     END;
  2025.     RotateCursor(TickCount - oldTicks);
  2026. END; {SFFilter}
  2027.  
  2028. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2029. {$S Open}
  2030. FUNCTION SFGetHook(MySFItem: INTEGER; dialog: DialogPtr): INTEGER;
  2031.  
  2032. CONST
  2033.     kFirstTime =     -1;                    {item is -1 first time into hook}
  2034.     reDrawList =    101;                    {returning 101 as item number will
  2035.                                                  cause the file list to redraw}
  2036. VAR
  2037.     kind:                INTEGER;
  2038.     cntl:                ControlHandle;
  2039.     r:                    Rect;
  2040.  
  2041. BEGIN
  2042.     SFGetHook := MySFitem;
  2043.     GetDItem(dialog, rSndOnlyCheckBox, kind, Handle(cntl), r);
  2044.     CASE MySFItem OF
  2045.  
  2046.         kFirstTime: BEGIN
  2047.             IF gSndFilesOnly THEN
  2048.                 SetCtlValue(cntl, kCntlOn)
  2049.             ELSE
  2050.                 SetCtlValue(cntl, kCntlOff);
  2051.         END;
  2052.  
  2053.         rSndOnlyCheckBox: BEGIN
  2054.             IF GetCtlValue(cntl) = kCntlOff THEN BEGIN
  2055.                 SetCtlValue(cntl, kCntlOn);
  2056.                 gSndFilesOnly:= TRUE;
  2057.             END ELSE BEGIN
  2058.                 SetCtlValue(cntl, kCntlOff);
  2059.                 gSndFilesOnly:= FALSE;
  2060.             END;
  2061.             SFGetHook:= reDrawList;
  2062.         END;
  2063.     END;
  2064. END; {SFGetHook}
  2065.  
  2066. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2067. {$S Open}
  2068. PROCEDURE OpenSoundDoc;
  2069.  
  2070. {Believe it or not, but this turned out to be one of the more difficult
  2071.  routines to write.  This was the best approach I could thing of to avoid
  2072.  serious problems.  I don’t center the Standard File dialog because it
  2073.  wouldn’t be under the File menu where the user probably has the mouse.  I
  2074.  use OpenRFPerm because it allows for permissions and doesn’t depend on the
  2075.  current directory.  First problem with opening a resource file was to
  2076.  check if the file already being open.  Read Tech Notes #116 and #185.
  2077.  GetFInfo seems to do the trick.  At least it does report all files that
  2078.  are open on this machine.  It may be incorrect for files on AppleShare
  2079.  opened by other machines.  What I’m worried about is when opening a
  2080.  resource file for the second time on the same machine may return the
  2081.  previous opener’s resource map.  This is very dangerous, and if the second
  2082.  opener calls CloseResFile there will be a crash.  I want to be friendly
  2083.  and if the user tries to open the file the second time and I’ve already
  2084.  got it on the screen, then I’ll bring that window forward.  To test for
  2085.  this, I compare the file’s name, DirID and vRefNum.  The vRefNum is
  2086.  dynamic and needs to be converted into a volume name if I were to save
  2087.  this information for future use.
  2088.  
  2089.  There are a couple pitfalls, even with this method.  The user can open the
  2090.  file, then move it to another directory.  This same thing confuses all
  2091.  other applications I’ve tested.  Opening a resource file will allocate a
  2092.  resource map handle into my heap, which may be large depending on the
  2093.  number of resources in that file.  Additionally this loads all resources
  2094.  marked “preload.”  So I set ResLoad to FALSE to prevent the preloading.  I
  2095.  test if the amount of memory I believe my document will require is
  2096.  available after opening the resource file.  If true, I test if there are
  2097.  any sound resources in that file and if not alert the user.  After all
  2098.  this, create the new document.  If after creating the new document I find
  2099.  that memory is too low, will close it and return an error.  If it does
  2100.  fail, then close the file before anything else or there may not be enough
  2101.  memory to show the alert.  All of these tests created a number of
  2102.  IF-THEN-ELSE blocks and became unyielding.  C programmers get a break, so
  2103.  gimme me one too.  I use the MPW Pascal EXIT.
  2104.  
  2105.  BUG NOTE: Don’t open a resource file that is already open.  OpenResFile
  2106.  may return an existing resource map when it gets opWrErr from the file
  2107.  system.  If this happens, the resource file will not be unique and this
  2108.  is very bad.  Another problem is if I get a read-only path and someone
  2109.  else opens it for read/write.  This is also very bad.  Read Tech Notes
  2110.  #116 and #185 hint at this problem, but I think a more comprehensive one
  2111.  is in order.
  2112.  
  2113.  BUG NOTE: GetWDInfo fails with nsvErr if the working directory returned
  2114.  from Standard File is the root of an A/UX volume.  I could work around
  2115.  this,  but it would be dependant on the current version of A/UX.  Read
  2116.  Tech Note #229.  I believe this is also true for TOPS.}
  2117.  
  2118. VAR
  2119.     fPBRec:            ParamBlockRec;
  2120.     window:            WindowPtr;
  2121.     reply:             SFReply;
  2122.     fileTypes:        SFTypeList;                            {not used, just a placeholder}
  2123.     aPoint:             Point;
  2124.     dirID, procID:    LONGINT;
  2125.     resFileRef,
  2126.     vRefNum,
  2127.     numSnds:            INTEGER;
  2128.     theErr:            OSErr;
  2129.  
  2130. BEGIN
  2131.     SetPt(aPoint, kSFTop, kSFLeft);
  2132.     SpinCursor(0);                                            {get the spinning cursor ready}
  2133.     SFPGetFile(aPoint, '', @SFFilter, -1, fileTypes,
  2134.                     @SFGetHook, reply, rSFPGetFileDLOG, NIL);
  2135.     IF reply.good THEN BEGIN
  2136.         WITH fPBRec DO BEGIN                                {prepare a paramBlock}
  2137.             ioCompletion:= NIL;
  2138.             ioNamePtr:= @reply.fName;
  2139.             ioVRefNum:= reply.vRefNum;
  2140.             ioFVersNum:= 0;
  2141.             ioFDirIndex:= 0;
  2142.         END;                                                    {get file location}
  2143.         theErr:= GetWDInfo(reply.vRefNum, vRefNum, dirID, procID);
  2144.         IF theErr <> noErr THEN BEGIN
  2145.             AlertUser(theErr, sStandardErr);            {this fails at the root on A/UX}
  2146.             Exit(OpenSoundDoc);
  2147.         END;
  2148.         theErr:= PBGetFInfo(@fPBRec, NOT kFSAsynch); {fPBRec on stack, synch only}
  2149.         IF theErr = noErr THEN BEGIN
  2150.             IF BTst(fPBRec.ioFlAttrib, kResForkOpenBit) THEN BEGIN
  2151.                 IF OpenByApp(vRefNum, dirID, @reply.fName, window) THEN
  2152.                     SelectWindow(window)                    {I opened this one, select it}
  2153.                 ELSE
  2154.                     AlertUser(noErr, sCurInUseErr);    {in use by someone else}
  2155.                 Exit(OpenSoundDoc);
  2156.             END;
  2157.         END ELSE BEGIN
  2158.             AlertUser(theErr, sStandardErr);            {PBGetFInfo failed}
  2159.             Exit(OpenSoundDoc);
  2160.         END;
  2161.         SetResLoad(FALSE);                                {don’t load any resources}
  2162.         resFileRef:= OpenRFPerm(reply.fName, reply.vRefNum, fsCurPerm);
  2163.         theErr:= ResError;                                {save error, if any}
  2164.         SetResLoad(TRUE);                                    {restore ResLoad state}
  2165.         UseResFile(gAppResRef);                            {changes ResErr}
  2166.         IF resFileRef = -1 THEN BEGIN                    {error from OpenRFPerm}
  2167.             AlertUser(theErr, sResErr);                {resFile open error}
  2168.             Exit(OpenSoundDoc);
  2169.         END;
  2170.         UseResFile(resFileRef);
  2171.         numSnds:= Count1Resources('snd ');            {count only its resouces}
  2172.         UseResFile(gAppResRef);                            {restore our resource file}
  2173.         IF numSnds < 1 THEN BEGIN
  2174.             CloseResFile(resFileRef);                    {close it before Alert}
  2175.             AlertUser(resNotFound, sNoSndsErr);        {didn’t find any sounds}
  2176.             Exit(OpenSoundDoc);
  2177.         END;
  2178.         IF FailLowMemory(kMemForSndDoc) THEN BEGIN
  2179.             CloseResFile(resFileRef);                    {close it before Alert}
  2180.             AlertUser(memFullErr, sLowMemory);
  2181.             Exit(OpenSoundDoc);
  2182.         END;
  2183.         theErr:= NewSoundDoc(resFileRef, @reply.fName, vRefNum, dirID);
  2184.         IF theErr <> noErr THEN BEGIN
  2185.             CloseResFile(resFileRef);                     {close it before Alert}
  2186.             AlertUser(theErr, sNewDocErr);             {couldn’t create new doc}
  2187.         END;
  2188.     END;
  2189. END; {OpenSoundDoc}
  2190.  
  2191. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2192. {$S Main}
  2193. PROCEDURE DrawAboutWindow(window: WindowPtr);
  2194.  
  2195. {Draw the contents of the about window in response to an update event.  At
  2196.  this point, BeginUpdate has been called which sets the window’s visRgn to
  2197.  clip drawing only where it needs to be done.  I have some text to draw, an
  2198.  icon, a picture, and a default button with its outline.  If I have a color
  2199.  icon handle I’ll call PlotCIcon.  I offset the picture to draw to the
  2200.  right of the icon.  The text will appear in a rectangle as large as the
  2201.  window, but below the icon and above the button.  This allows me the
  2202.  change the text and if needed change the size of the window’s rectangle to
  2203.  compensate.  I won’t have to recompile any code.  Some people use dialogs
  2204.  because of this, but I’m demonstrating how it can be done without them.  I
  2205.  use UpdtControl to avoid needless drawing that happens with DrawControls.
  2206.  It not only runs faster but doesn’t flicker.}
  2207.  
  2208. VAR
  2209.     theRect:            Rect;
  2210.  
  2211. BEGIN
  2212.     PenNormal;
  2213.     SetRect(theRect, kIconLeft, kIconTop, kIconRight, kIconBot);
  2214.     IF AboutWPeek(window)^.iconIsColor THEN
  2215.         PlotCIcon(theRect, CIconHandle(AboutWPeek(window)^.appIcon))
  2216.     ELSE
  2217.         PlotIcon(theRect, AboutWPeek(window)^.appIcon);
  2218.  
  2219.     theRect:= PicHandle(AboutWPeek(window)^.appPict)^^.picFrame;
  2220.     OffsetRect(theRect, -theRect.left + kIconRight + kIconPictGap,
  2221.                               -theRect.top + kIconTop);
  2222.     DrawPicture(PicHandle(AboutWPeek(window)^.appPict), theRect);
  2223.  
  2224.     WITH window^.portRect DO
  2225.         SetRect(theRect, left, kIconBot, right, bottom - kDafaultButSizeH);
  2226.     InsetRect(theRect, kMsgInset, kMsgInset);
  2227.     HLock(AboutWPeek(window)^.comment);
  2228.     TextBox(Ptr(ORD(AboutWPeek(window)^.comment^) + 1),
  2229.                 LENGTH(StringHandle(AboutWPeek(window)^.comment)^^),
  2230.                 theRect, teJustCenter);
  2231.     HUnlock(AboutWPeek(window)^.comment);
  2232.  
  2233.     UpdtControl(window, window^.visRgn);
  2234.     DoButtonOutline(WindowPeek(window)^.ControlList);
  2235. END; {DrawAboutWindow}
  2236.  
  2237. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2238. {$S Main}
  2239. PROCEDURE DoAbout;
  2240.  
  2241. {First thing to do is call KillSound to stop any sound in progress and
  2242.  close the status window.  If there’s enough memory available, I’ll play
  2243.  the about sound.  This is sound is asynchronous and will automatically be
  2244.  disposed of when completed.  There is an icon, taken from the bundle
  2245.  resources, and a picture.  The text is taken from a string resource.  It
  2246.  contains a couple variables just like ParamText would want.  I get the
  2247.  current name of the application from the AppParms.  This is the name of
  2248.  the application as specified by the user.  I read in my 'vers' resource
  2249.  to get the current version to be displayed in the window.  Read Tech Note
  2250.  189 for more details on the vers resource.  I think these are two
  2251.  important things to show in the about box.  These two portions of the text
  2252.  are put into place with my own version of ParamText.   I tried all of this
  2253.  with a standard dialog, but had trouble.  Sometimes the color icon didn’t
  2254.  show up.  Trying to center justify text with a statText item wasn’t really
  2255.  possible.  On the Mac SE, for some unknown reason, TESetJust failed to
  2256.  center the textH of the dialog.  I also found that this call would set the
  2257.  dialog’s text back to Chicago even after I had called TextFont.  So, I
  2258.  gave up and did everything myself.  This is a demonstration of how to
  2259.  create a dialog without using the Dialog Manager.}
  2260.  
  2261. VAR
  2262.     verNum,
  2263.     userName:        Str255;
  2264.     aboutPtr:        Ptr;
  2265.     aboutPeek:        AboutWPeek;
  2266.     control:            ControlHandle;
  2267.     h:                    Handle;
  2268.     curVersion:        VersRecHndl;
  2269.     refNum:            INTEGER;
  2270.     theErr:            OSErr;
  2271.     ignore:            BOOLEAN;
  2272.  
  2273. BEGIN
  2274.     KillSound;
  2275.     aboutPtr:= NewPtrClear(SIZEOF(AboutWindow));
  2276.     IF aboutPtr <> NIL THEN BEGIN
  2277.         aboutPeek:= AboutWPeek(GetCenteredWindow(rAboutWindow,
  2278.                                                 aboutPtr, Pointer(-1)));
  2279.         SetWRefCon(WindowPtr(aboutPeek), rAboutWindow);
  2280.         curVersion:= VersRecHndl(Get1Resource('vers', 1));
  2281.         IF curVersion <> NIL THEN
  2282.             verNum:= curVersion^^.shortVersion                {get version string}
  2283.         ELSE
  2284.             verNum:= '';                                            {at least initialize it}
  2285.         GetAppParms(userName, refNum, h);
  2286.         aboutPeek^.appPict:= Get1Resource('PICT', rAppPict);
  2287.         aboutPeek^.comment:= Get1Resource('STR ', rAboutText);
  2288.         aboutPeek^.appIcon:= NIL;
  2289.         aboutPeek^.iconIsColor:= TRUE;
  2290.         IF gMac.hasColorQD THEN
  2291.             aboutPeek^.appIcon:= Handle(GetCIcon(rMoofIcon));
  2292.         IF aboutPeek^.appIcon = NIL THEN BEGIN
  2293.             aboutPeek^.appIcon:= Get1Resource('ICON', rMoofIcon);
  2294.             aboutPeek^.iconIsColor:= TRUE;
  2295.         END;
  2296.         control:= GetNewControl(rAboutOkCntl, WindowPtr(aboutPeek));
  2297.  
  2298.         IF (aboutPeek^.appPict <> NIL) | (aboutPeek^.comment <> NIL)
  2299.          | (aboutPeek^.appIcon <> NIL) | (control <> NIL) THEN BEGIN
  2300.             HNoPurge(aboutPeek^.appPict);                        {must keep them around}
  2301.              HNoPurge(aboutPeek^.comment);
  2302.             HNoPurge(aboutPeek^.appIcon);
  2303.             MyParamText(StringHandle(aboutPeek^.comment), @userName, @verNum);
  2304.             IF NOT FailLowMemory(0) THEN
  2305.                 theErr:= AsynchSndPlay(Get1Resource('snd ', rMoofSound));
  2306.         END ELSE BEGIN                                                {couldn’t build window}
  2307.             DoErrorSound(1);
  2308.             ignore:= DoCloseWindow(WindowPtr(aboutPeek));
  2309.         END;
  2310.     END ELSE
  2311.         DoErrorSound(1);
  2312. END; {DoAbout}
  2313.  
  2314. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2315. {$S Main}
  2316. PROCEDURE PlaySelectedSnd(sndDoc: SndDocPeek; message: INTEGER);
  2317.  
  2318. {Get the selected sound and pass it to AsynchSndPlay or HyperSndPlay.  This
  2319.  depends on the normal flag.  HyperCard’s method is not normal.  This is
  2320.  the HyperCard version of playing a sound.  It resamples any sound to
  2321.  middle C.  If the resource is too large to fit in memory, I’ll get a NIL
  2322.  handle error from the Sound Unit.  It might be nice to test for this
  2323.  before calling the Sound Unit and telling the user they’re too low on
  2324.  memory, but the unit is robust enough and reports the error.  It’s
  2325.  important to call KillSound to dispose of any data that was
  2326.  allocated if an error were to occur.}
  2327.  
  2328. VAR
  2329.     sndHandle:    Handle;
  2330.     theErr:        OSErr;
  2331.  
  2332. BEGIN
  2333.     theErr:= GetSelection(sndDoc, sndHandle);
  2334.     IF theErr = noErr THEN BEGIN
  2335.         IF message = sPlayingMsg THEN
  2336.             theErr:= AsynchSndPlay(sndHandle)
  2337.         ELSE
  2338.             theErr:= HyperSndPlay(sndHandle);
  2339.     END;
  2340.     IF theErr = noErr THEN BEGIN
  2341.         sndDoc^.sndInUse:= TRUE;                    {this document has a snd in use}
  2342.         ShowStatusWindow(message);
  2343.     END ELSE BEGIN
  2344.         KillSound;
  2345.         AlertUser(theErr, sSoundErr);
  2346.     END;
  2347. END; {PlaySelectedSnd}
  2348.  
  2349. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2350. {$S Main}
  2351. PROCEDURE PlaySndSong(sndDoc: SndDocPeek; sndID: INTEGER);
  2352.  
  2353. {Given a sound resource ID, this will get my song resource and call the
  2354.  Sound Unit to use that sampled sound and song to play a tune.  This
  2355.  application will play one of two songs for sampled sounds.  If any error
  2356.  is encountered, I call KillSound to dispose of all data.}
  2357.  
  2358. VAR
  2359.     chan:             SndChannelPtr;
  2360.     sndInst,
  2361.     sndSong:            Handle;
  2362.     theErr:            OSErr;
  2363.  
  2364. BEGIN
  2365.     theErr:= GetSelection(sndDoc, sndInst);
  2366.     IF theErr = noErr THEN BEGIN
  2367.         sndSong:= Get1Resource('snd ', sndID);
  2368.         theErr:= ResError;                                {save any error}
  2369.         IF sndSong <> NIL THEN BEGIN
  2370.             theErr:= GetSampleChan(chan, kInitNone, sndInst);
  2371.             IF theErr = noErr THEN BEGIN
  2372.                 sndDoc^.sndInUse:= TRUE;                {this document has a snd in use}
  2373.                 theErr:= PlaySong(chan, sndSong);
  2374.             END;
  2375.         END;
  2376.     END;
  2377.     IF theErr = noErr THEN BEGIN
  2378.         IF sndID = rScaleSnd THEN
  2379.             ShowStatusWindow(sScaleMsg)
  2380.         ELSE                                                    {I can play scales or a melody}
  2381.             ShowStatusWindow(sMelodyMsg);
  2382.     END ELSE BEGIN                                            {catch any errors}
  2383.         KillSound;
  2384.         AlertUser(theErr, sSoundErr);
  2385.     END;
  2386. END; {PlaySndSong}
  2387.  
  2388. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2389. {$S Main}
  2390. PROCEDURE PlayNoteSong(sndID: INTEGER);
  2391.  
  2392. {Given a sound resource ID, this will get my song resource and call the
  2393.  Sound Unit to use the note synthesizer and song to play a tune.  I request
  2394.  the note snth’s timbre (sounds like “tom burr”).  If any error is
  2395.  encountered, I call KillSound to dispose of all data.}
  2396.  
  2397. VAR
  2398.     theErr:            OSErr;
  2399.     sndSong:            Handle;
  2400.     chan:             SndChannelPtr;
  2401.  
  2402. BEGIN
  2403.     sndSong:= Get1Resource('snd ', sndID);
  2404.     IF (sndSong <> NIL) THEN BEGIN
  2405.         theErr:= GetNoteChan(chan, kPreferredTimbre);
  2406.         IF theErr = noErr THEN BEGIN
  2407.             theErr:= PlaySong(chan, sndSong);
  2408.             IF theErr = noErr THEN BEGIN
  2409.                 IF sndID = rScaleSnd THEN
  2410.                     ShowStatusWindow(sScaleMsg)
  2411.                 ELSE                                        {I play scales or a melody}
  2412.                     ShowStatusWindow(sMelodyMsg);
  2413.             END;
  2414.         END;
  2415.         IF theErr <> noErr THEN BEGIN                {catch any errors}
  2416.             KillSound;
  2417.             AlertUser(theErr, sSoundErr);
  2418.         END;
  2419.     END ELSE
  2420.         AlertUser(ResError, sResErr);            {I’ll return the resource error}
  2421. END; {PlayNoteSong}
  2422.  
  2423. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2424. {$S Main}
  2425. PROCEDURE PlayNoteTimbres;
  2426.  
  2427. {This is a demonstration of the note synth’s tone qualities (or the lack
  2428.  there of).  This simply loops through timbres sending alternating note and
  2429.  rest commands.  Once all the notes have been sent, then I need to send a
  2430.  callBackCmd to signal the SoundUnit to dispose of the channel.  Well,
  2431.  actually the SoundUnit will set a global flag that the application will be
  2432.  polling for later in the event loop.  Once this happens, or if any errors
  2433.  are encountered along the way, KillSound will be called.  One very
  2434.  disappointing aspect to changing the timbre is that the Mac Plus or SE
  2435.  cannot handle this while a note is sounding.  The Apple Sound Chip can and
  2436.  if you wanted to remove the rests try this routine on a Mac II, for
  2437.  example, you can hear a continuous note while the timbre changes.  Try
  2438.  this on a Mac Plus and you’ll hear garbage.  I’d show this myself, but how
  2439.  do I determine if the Mac has the ASC?
  2440.  
  2441.  BUG NOTE: There is problem when the final sound command is a noteCmd.
  2442.  The note will continue to sound, looping forever, until a quietCmd is sent
  2443.  or the channel is disposed of.  To prevent unwanted looping, I send a
  2444.  quietCmd after all notes.}
  2445.  
  2446. VAR
  2447.     chan:             SndChannelPtr;
  2448.     timbre:            INTEGER;
  2449.     theErr:            OSErr;
  2450.  
  2451. BEGIN
  2452.     theErr:= GetNoteChan(chan, kPreferredTimbre);
  2453.     IF theErr = noErr THEN BEGIN
  2454.         ShowStatusWindow(sTimbresMsg);
  2455.         FOR timbre:= kSineWave TO kSquareWave DO BEGIN
  2456.             theErr:= SetNoteTimbre(chan, timbre, kWait);
  2457.             IF theErr = noErr THEN
  2458.                 theErr:= SendNote(chan, kOneSecond DIV 2, kFullAmp + kOctave7 + Akey);
  2459.             IF theErr = noErr THEN
  2460.                 theErr:= SendRest(chan, kOneSecond DIV 10);
  2461.             timbre:= timbre + 8;                            {skip a few more timbres}
  2462.             IF theErr <> noErr THEN                        {if there was an error...}
  2463.                 timbre:= kSquareWave + 1;                {get out of the loop}
  2464.         END;
  2465.     END;
  2466.     IF theErr = noErr THEN
  2467.         theErr:= SoundComplete(chan)
  2468.     ELSE BEGIN                                                {catch any errors}
  2469.         KillSound;
  2470.         AlertUser(theErr, sSoundErr);
  2471.     END;
  2472. END; {PlayNoteTimbres}
  2473.  
  2474. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2475. {$S Main}
  2476. PROCEDURE PlayWaveScale;
  2477.  
  2478. {This demonstrates the wave table synthesizers.  First thing to do is
  2479.  obtain a wave cycle and the 'snd ' resource containing a song to be
  2480.  played.  Then I’m ready to get the four wave channels and install the
  2481.  chosen wave.  Once the wave is installed into the channel I can dispose of
  2482.  the memory used to create the wave, since the Sound Manager will copy it
  2483.  to its internal buffers.  At this point I’m ready to play the song.  It’s
  2484.  not easy to hear four wave synths playing the same note with the same wave
  2485.  table.  I was going to add a modifier to the channel that would transpose
  2486.  each channels note, but I found a bug.
  2487.  
  2488.  BUG NOTE: Installing a modifier to one of the wave table channels caused
  2489.  the channel to fail.  My normal sequence of events is this: I synchronize
  2490.  the four channels, send all the note commands, end this with the
  2491.  callBackCmd, and finally release the channels to play their queues.  When
  2492.  I added a modifier, the callBackCmd was the first command to be processed.
  2493.  This caused my completion routines to be called and before the channel
  2494.  made any sound it was disposed.  I tried this without the callBackCmd and
  2495.  the channel never processed any commands.
  2496.  
  2497.  BUG NOTE: The wave table synthesizer is not working on a non-Apple Sound
  2498.  chip based Mac.  At least not so far with any System 6.0x releases.  This
  2499.  leaves the Mac Plus/SE without four tone polyphonic sound.}
  2500.  
  2501. VAR
  2502.     chan1, chan2,
  2503.     chan3, chan4:        SndChannelPtr;
  2504.     sndSong,
  2505.     waveHandle:            Handle;
  2506.     waveTablePtr:        Ptr;
  2507.     offSet:                LONGINT;
  2508.     sndType,
  2509.     waveLength:            INTEGER;
  2510.     theErr:                OSErr;
  2511.  
  2512. BEGIN
  2513.     IF gMac.machineType IN [env512KE, envMacPlus, envSE] THEN BEGIN
  2514.         AlertUser(badChannel, sWavesBroken);        {waves not available}
  2515.         EXIT(PlayWaveScale);                                {we’re out of here}
  2516.     END;
  2517.     sndSong:= Get1Resource('snd ', rScaleSnd);
  2518.     IF sndSong <> NIL THEN BEGIN
  2519.         waveHandle:= Get1Resource('snd ', rTenorVox);
  2520.         theErr:= HoldSnd(waveHandle);
  2521.         IF theErr = noErr THEN BEGIN
  2522.             offSet:= GetSndDataOffset(waveHandle, sndType, waveLength);
  2523.             waveTablePtr:= Ptr(ORD4(waveHandle^) + offSet);
  2524.             theErr:= GetWaveChans(chan1, chan2, chan3, chan4);
  2525.             IF theErr = noErr THEN BEGIN
  2526.                 theErr:= InstallWave(chan1, waveTablePtr, waveLength);
  2527.                 IF theErr = noErr THEN BEGIN
  2528.                     theErr:= InstallWave(chan2, waveTablePtr, waveLength);
  2529.                     IF theErr = noErr THEN BEGIN
  2530.                         theErr:= InstallWave(chan3, waveTablePtr, waveLength);
  2531.                         IF theErr = noErr THEN
  2532.                             theErr:= InstallWave(chan4, waveTablePtr, waveLength);
  2533.                     END;
  2534.                 END;
  2535.             END;
  2536.             HUnlock(waveHandle);
  2537.             HPurge(waveHandle);
  2538.             IF theErr = noErr THEN
  2539.                 theErr:= Play4Waves(chan1, chan2, chan3, chan4,
  2540.                                           sndSong, sndSong, sndSong, sndSong);
  2541.             IF theErr = noErr THEN
  2542.                 ShowStatusWindow(sScaleMsg)
  2543.             ELSE BEGIN                                {catch any sound unit errors}
  2544.                 KillSound;
  2545.                 AlertUser(theErr, sSoundErr);
  2546.             END;
  2547.         END ELSE
  2548.             AlertUser(theErr, sResErr);        {couldn’t get waveHandle}
  2549.     END ELSE
  2550.         AlertUser(ResError, sResErr);            {couldn’t get song}
  2551. END;
  2552.  
  2553. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2554. {$S Main}
  2555. FUNCTION GetSndSongs(sndSongID1, sndSongID2, sndSongID3, sndSongID4: INTEGER;
  2556.                             VAR sndSong1, sndSong2, sndSong3, sndSong4: Handle): OSErr;
  2557.  
  2558. {This is a utility routine used to obtain the four snd resources that
  2559.  contain parts of a song.  Nothing much to do other then get the resource
  2560.  and do error checking.}
  2561.  
  2562. BEGIN
  2563.     GetSndSongs:= noErr;                                        {initialize result}
  2564.     sndSong1:= Get1Resource('snd ', sndSongID1);     {get all the snds}
  2565.     IF sndSong1 <> NIL THEN BEGIN
  2566.         sndSong2:= Get1Resource('snd ', sndSongID2);
  2567.         IF sndSong2 <> NIL THEN BEGIN
  2568.             sndSong3:= Get1Resource('snd ', sndSongID3);
  2569.             IF sndSong3 <> NIL THEN
  2570.                 sndSong4:= Get1Resource('snd ', sndSongID4);
  2571.         END;
  2572.     END;
  2573.     IF (sndSong1 = NIL) | (sndSong2 = NIL)
  2574.      | (sndSong3 = NIL) | (sndSong4 = NIL) THEN
  2575.         GetSndSongs:= ResErr;                                {return resource error}
  2576. END;
  2577.  
  2578. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2579. {$S Main}
  2580. FUNCTION InstallWaveSnds(chan1, chan2, chan3, chan4: SndChannelPtr;
  2581.                                     waveID1, waveID2, waveID3, waveID4: INTEGER): OSErr;
  2582.  
  2583. {This routine is a utility I’m using to prepare four wave table channels.
  2584.  First thing to do is obtain a wave table data I stored in a set of 'snd '
  2585.  resources.  Then I’m ready to install these wave tables into the four wave
  2586.  channels.  Once the waves are installed into the channel I can dispose of
  2587.  the memory used to create each wave, since the Sound Manager will copy
  2588.  them to its internal buffers.  At this point the channels are ready to
  2589.  play sounds.}
  2590.  
  2591. VAR
  2592.     waveSnd1, waveSnd2,
  2593.     waveSnd3, waveSnd4:    Handle;
  2594.     wavePtr:                    Ptr;
  2595.     offSet:                    LONGINT;
  2596.     waveLgth, sndType:    INTEGER;
  2597.     theErr:                    OSErr;
  2598.  
  2599. BEGIN
  2600.     waveSnd1:= Get1Resource('snd ', waveID1);        {get em and hold em down}
  2601.     theErr:= HoldSnd(waveSnd1);
  2602.     IF theErr = noErr THEN BEGIN
  2603.         waveSnd2:= Get1Resource('snd ', waveID2);
  2604.         theErr:= HoldSnd(waveSnd2);
  2605.         IF theErr = noErr THEN BEGIN
  2606.             waveSnd3:= Get1Resource('snd ', waveID3);
  2607.             theErr:= HoldSnd(waveSnd3);
  2608.             IF theErr = noErr THEN BEGIN
  2609.                 waveSnd4:= Get1Resource('snd ', waveID4);
  2610.                 theErr:= HoldSnd(waveSnd4);
  2611.             END;
  2612.         END;
  2613.     END;
  2614.     InstallWaveSnds:= theErr;                            {return the error}
  2615.     IF theErr <> noErr THEN
  2616.         EXIT(InstallWaveSnds);                            {we’re out of here}
  2617.                                                                 {catch the waves}
  2618.     offSet:= GetSndDataOffset(waveSnd1, sndType, waveLgth);
  2619.     wavePtr:= Ptr(ORD4(waveSnd1^) + offSet);
  2620.     theErr:= InstallWave(chan1, wavePtr, waveLgth);
  2621.     IF theErr = noErr THEN BEGIN
  2622.         offSet:= GetSndDataOffset(waveSnd2, sndType, waveLgth);
  2623.         wavePtr:= Ptr(ORD4(waveSnd2^) + offSet);
  2624.         theErr:= InstallWave(chan2, wavePtr, waveLgth);
  2625.         IF theErr = noErr THEN BEGIN
  2626.             offSet:= GetSndDataOffset(waveSnd3, sndType, waveLgth);
  2627.             wavePtr:= Ptr(ORD4(waveSnd3^) + offSet);
  2628.             theErr:= InstallWave(chan3, wavePtr, waveLgth);
  2629.             IF theErr = noErr THEN BEGIN
  2630.                 offSet:= GetSndDataOffset(waveSnd4, sndType, waveLgth);
  2631.                 wavePtr:= Ptr(ORD4(waveSnd4^) + offSet);
  2632.                 theErr:= InstallWave(chan4, wavePtr, waveLgth);
  2633.             END;
  2634.         END;
  2635.     END;
  2636.     HUnlock(waveSnd1);                                    {done with resources}
  2637.     HPurge(waveSnd1);
  2638.     HUnlock(waveSnd2);
  2639.     HPurge(waveSnd2);
  2640.     HUnlock(waveSnd3);
  2641.     HPurge(waveSnd3);
  2642.     HUnlock(waveSnd4);
  2643.     HPurge(waveSnd4);
  2644.     InstallWaveSnds:= theErr;                            {return the error}
  2645. END;
  2646.  
  2647. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2648. {$S Main}
  2649. PROCEDURE PlayWaveMelody;
  2650.  
  2651. {This is the demonstration of the wave table synthesizers.  This will get
  2652.  four snd resources that contain parts to a song.  Then I get the four wave
  2653.  table channels.  With these four channels, I install two other snd
  2654.  resources that contain wave table data.  Once the four songs, four
  2655.  channels, and two wave tables are ready then I play the song.
  2656.  
  2657.  BUG NOTE: The wave table synthesizer is not working on a non-Apple Sound
  2658.  chip based Mac.  At least not so far with any System 6.0x release.  This
  2659.  leaves the Mac Plus/SE without four tone polyphonic sound.}
  2660.  
  2661. VAR
  2662.     sndSong1, sndSong2,
  2663.     sndSong3, sndSong4:    Handle;
  2664.     chan1, chan2,
  2665.     chan3, chan4:            SndChannelPtr;
  2666.     theErr:                    OSErr;
  2667.  
  2668. BEGIN
  2669.     theErr:= noErr;
  2670.     IF gMac.machineType IN [env512KE, envMacPlus, envSE] THEN BEGIN
  2671.         AlertUser(badChannel, sWavesBroken);            {waves not available}
  2672.         EXIT(PlayWaveMelody);                                {we’re out of here}
  2673.     END;
  2674.     theErr:= GetSndSongs(rMelodyPart1, rMelodyPart2, rMelodyPart3, rMelodyPart4,
  2675.                                 sndSong1, sndSong2, sndSong3, sndSong4);
  2676.     IF theErr <> noErr THEN BEGIN
  2677.         AlertUser(theErr, sResErr);                {return the error}
  2678.         EXIT(PlayWaveMelody);
  2679.     END;
  2680.     theErr:= GetWaveChans(chan1, chan2, chan3, chan4);
  2681.     IF theErr = noErr THEN BEGIN
  2682.         theErr:= InstallWaveSnds(chan1, chan2, chan3, chan4,
  2683.                                     rWaveMelody, rWaveHarmony, rWaveHarmony, rWaveHarmony);
  2684.         IF theErr = noErr THEN
  2685.             theErr:= Play4Waves(chan1, chan2, chan3, chan4,
  2686.                                           sndSong1, sndSong2, sndSong3, sndSong4);
  2687.     END;
  2688.     IF theErr = noErr THEN
  2689.         ShowStatusWindow(sMelodyMsg)
  2690.     ELSE BEGIN                                        {catch any errors}
  2691.         KillSound;
  2692.         AlertUser(theErr, sSoundErr);
  2693.     END;
  2694. END;
  2695.  
  2696. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2697. {$S Main}
  2698. PROCEDURE PlayWaveSATB;
  2699.  
  2700. {This is the demonstration of the wave table synthesizers.  This will get
  2701.  four snd resources that contain parts to a song.  Then I get the four wave
  2702.  table channels.  With these four channels, I install four other snd resources
  2703.  that contain wave table data.  Once the four songs, four channels, and
  2704.  four wave tables are ready then I play the song.  By the way, SATB stands
  2705.  for Soprano, Alto, Tenor, and Bass.  It’s standard music-speak.
  2706.  
  2707.  BUG NOTE: The wave table synthesizer is not working on a non-Apple Sound
  2708.  chip based Mac.  At least not so far with any System 6.0x release.  This
  2709.  leaves the Mac Plus/SE without four tone polyphonic sound.}
  2710.  
  2711. VAR
  2712.     sndSong1, sndSong2,
  2713.     sndSong3, sndSong4:    Handle;
  2714.     chan1, chan2,
  2715.     chan3, chan4:            SndChannelPtr;
  2716.     theErr:                    OSErr;
  2717.  
  2718. BEGIN
  2719.     theErr:= noErr;
  2720.     IF gMac.machineType IN [env512KE, envMacPlus, envSE] THEN BEGIN
  2721.         AlertUser(badChannel, sWavesBroken);            {waves not available}
  2722.         EXIT(PlayWaveSATB);                                    {we’re out of here}
  2723.     END;
  2724.     theErr:= GetSndSongs(rCounterPt1, rCounterPt2, rCounterPt3, rCounterPt4,
  2725.                                 sndSong1, sndSong2, sndSong3, sndSong4);
  2726.     IF theErr <> noErr THEN BEGIN
  2727.         AlertUser(theErr, sResErr);                        {return the error}
  2728.         EXIT(PlayWaveSATB);
  2729.     END;
  2730.     theErr:= GetWaveChans(chan1, chan2, chan3, chan4);
  2731.     IF theErr = noErr THEN BEGIN
  2732.         theErr:= InstallWaveSnds(chan1, chan2, chan3, chan4,
  2733.                                             rSopranoVox, rAltoVox, rTenorVox, rBassVox);
  2734.         IF theErr = noErr THEN
  2735.             theErr:= Play4Waves(chan1, chan2, chan3, chan4,
  2736.                                           sndSong1, sndSong2, sndSong3, sndSong4);
  2737.     END;
  2738.     IF theErr = noErr THEN
  2739.         ShowStatusWindow(sCounterPtMsg)
  2740.     ELSE BEGIN                                                    {catch any errors}
  2741.         KillSound;
  2742.         AlertUser(theErr, sSoundErr);
  2743.     END;
  2744. END;
  2745.  
  2746. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2747. {$S Main}
  2748. PROCEDURE AdjustMenus;
  2749.  
  2750. {Enable and disable menus based on the current state.  The user can only
  2751.  select enabled menu items so I set up all the menu items before calling
  2752.  MenuSelect or MenuKey, since these are the only times that a menu item
  2753.  can be selected. Note that MenuSelect is also the only time the user will
  2754.  see menu items. This approach to deciding what enable/disable state a menu
  2755.  item has the advantage of concentrating all the decision making in one
  2756.  routine, as opposed to being spread throughout the application.  Other
  2757.  application designs may take a different approach that may or may not be
  2758.  just as valid.}
  2759.  
  2760. VAR
  2761.      menu:        MenuHandle;
  2762.     window:    WindowPtr;
  2763.  
  2764. BEGIN
  2765.     window:= FrontWindow;
  2766.  
  2767.     menu:= GetMHandle(mFile);                        {the File menu and items}
  2768.     IF IsDAWindow(window) | IsDocWindow(window) THEN
  2769.         EnableItem(menu, iClose)
  2770.     ELSE
  2771.         DisableItem(menu, iClose);
  2772.  
  2773.     menu:= GetMHandle(mEdit);                        {the Edit menu and items}
  2774.     IF IsDAWindow(FrontWindow) THEN BEGIN
  2775.         EnableItem(menu, iUndo);
  2776.         EnableItem(menu, iCut);
  2777.         EnableItem(menu, iCopy);
  2778.         EnableItem(menu, iPaste);
  2779.         EnableItem(menu, iClear);
  2780.     END ELSE BEGIN
  2781.         DisableItem(menu, iUndo);
  2782.         DisableItem(menu, iCut);
  2783.         DisableItem(menu, iCopy);
  2784.         DisableItem(menu, iPaste);
  2785.         DisableItem(menu, iClear);
  2786.     END;
  2787. END; {AdjustMenus}
  2788.  
  2789.  
  2790. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2791. {$S Main}
  2792. PROCEDURE DoMenuCommand(menuResult: LONGINT);
  2793.  
  2794. {This is called when an item is chosen from the menu bar (after calling
  2795.  MenuSelect or MenuKey). It performs the right operation for each command.
  2796.  It is good to have both the result of MenuSelect and MenuKey go to
  2797.  one routine like this to keep everything organized.}
  2798.  
  2799. VAR
  2800.     menuID, menuItem,                        {resource ID and item of the selected menu}
  2801.     daRefNum:            INTEGER;
  2802.     daName:                Str255;
  2803.     ignore:                BOOLEAN;
  2804.  
  2805. BEGIN
  2806.     menuID:= HiWrd(menuResult);        {use MPW’s built-ins for efficiency...}
  2807.     menuItem:= LoWrd(menuResult);        {to get menu item number and menu number}
  2808.     CASE menuID OF
  2809.  
  2810.         mApple:
  2811.             CASE menuItem OF
  2812.                 iAbout:                        {bring up alert for About}
  2813.                     DoAbout;
  2814.                 OTHERWISE BEGIN            {all non-About items in this menu are DAs}
  2815.                     GetItem(GetMHandle(mApple), menuItem, daName);
  2816.                     daRefNum:= OpenDeskAcc(daName);
  2817.                 END;
  2818.             END;
  2819.  
  2820.         mFile:
  2821.             CASE menuItem OF
  2822.                 iOpen:
  2823.                     OpenSoundDoc;
  2824.                 iClose:
  2825.                     ignore:= DoCloseWindow(FrontWindow); {I don’t care if cancelled}
  2826.                 iQuit:
  2827.                     Terminate;
  2828.             END;
  2829.  
  2830.         mEdit:                            {call SystemEdit for DA editing & MultiFinder}
  2831.             ignore:= SystemEdit(menuItem - 1);    {since I don’t do any editing}
  2832.  
  2833.         mDemos:
  2834.             CASE menuItem OF
  2835.  
  2836.                 iNoteScale:
  2837.                     PlayNoteSong(rScaleSnd);
  2838.  
  2839.                 iNoteMelody:
  2840.                     PlayNoteSong(rMelodyPart1);
  2841.  
  2842.                 iNoteTimbre:
  2843.                     PlayNoteTimbres;
  2844.  
  2845.                 iWaveScale:
  2846.                     PlayWaveScale;
  2847.  
  2848.                 iWaveMelody:
  2849.                     PlayWaveMelody;
  2850.  
  2851.                 iWaveSATB:
  2852.                     PlayWaveSATB;
  2853.  
  2854.             END; {CASE menuItem OF}
  2855.  
  2856.     END; {CASE menuID OF}
  2857.     HiliteMenu(0);                        {unhighlight what MenuSelect or MenuKey hilited}
  2858. END; {DoMenuCommand}
  2859.  
  2860. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2861. {$S Main}
  2862. PROCEDURE ActivateSndCntls(sndDoc: SndDocPeek);
  2863.  
  2864. {Given a sound document, this routine goes through the control list looking
  2865.  for a control that needs to be activated, or deactivated what ever the
  2866.  case maybe.  The Play button is the default button, and it also needs its
  2867.  outline drawn.  The Stop button is always active on the front most window.
  2868.  This is true even if there is no selection made in the window’s list.  The
  2869.  Stop button is a global action, regardless of what is happening in the window.}
  2870.  
  2871. VAR
  2872.     control:            ControlHandle;
  2873.     cntlRefCon:        LONGINT;
  2874.     activate:        BOOLEAN;
  2875.  
  2876. BEGIN
  2877.     activate:= WindowPeek(sndDoc)^.hilited & HasSelection(sndDoc);
  2878.     control:= WindowPeek(sndDoc)^.ControlList;
  2879.     WHILE control <> NIL DO BEGIN
  2880.         cntlRefCon:= GetCRefCon(control);
  2881.         IF cntlRefCon IN [rPlaySndCntl, rHyperPlayCntl,
  2882.                                 rPlayScaleCntl, rMelodyCntl] THEN BEGIN
  2883.             IF activate THEN
  2884.                 HiliteControl(control, kCntlActivate)
  2885.             ELSE
  2886.                 HiliteControl(control, kCntlDeactivate);
  2887.             IF cntlRefCon = rPlaySndCntl THEN
  2888.                 DoButtonOutline(control);
  2889.         END; {IF cntlRefCon IN}
  2890.         IF cntlRefCon = rStopCntl THEN BEGIN
  2891.             IF WindowPeek(sndDoc)^.hilited THEN
  2892.                 HiliteControl(control, kCntlActivate)
  2893.             ELSE
  2894.                 HiliteControl(control, kCntlDeactivate);
  2895.         END; {cntlRefCon = rStopCntl}
  2896.     control:= control^^.nextControl;
  2897.     END; {WHILE control <> NIL}
  2898. END;
  2899.  
  2900. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2901. {$S Main}
  2902. PROCEDURE DrawSndWindow(window: WindowPtr);
  2903.  
  2904. {Draw the contents of the application window in response to an update
  2905.  event.  At this point, BeginUpdate has been called which sets the window’s
  2906.  visRgn to clip drawing only where it needs to be done.  I have the
  2907.  controls to draw, a list to update, and a default button to outline.  I
  2908.  use UpdtControl to avoid needless drawing that happens with DrawControls.
  2909.  It not only runs faster but doesn’t flicker.}
  2910.  
  2911.  VAR
  2912.     control:            ControlHandle;
  2913.     theRect:         Rect;
  2914.  
  2915. BEGIN
  2916.     PenNormal;
  2917.     LUpdate(window^.VisRgn, SndDocPeek(window)^.list);        {update list}
  2918.     theRect:= SndDocPeek(window)^.list^^.rView;                {frame the list}
  2919.     theRect.right:= theRect.right + kScrollBarWidth;
  2920.     InsetRect(theRect, kListFrameInset, kListFrameInset);
  2921.     FrameRect(theRect);
  2922.     UpdtControl(window, window^.visRgn);                        {update controls}
  2923.     control:= WindowPeek(window)^.ControlList;                {draw button outline}
  2924.     WHILE control <> NIL DO BEGIN
  2925.         IF GetCRefCon(control) = rPlaySndCntl THEN
  2926.             DoButtonOutline(control);
  2927.         control:= control^^.nextControl;
  2928.     END;
  2929. END; {DrawWindow}
  2930.  
  2931. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2932. {$S Main}
  2933. PROCEDURE DoKeyDown(key: CHAR; window: WindowPtr);
  2934.  
  2935. {When the user types a key, I check if it is one that I’m looking for.
  2936.  This routine only handles the non-command key events.  Here I’m looking
  2937.  for a arrow key or the return and enter keys for the default button.}
  2938.  
  2939. VAR
  2940.     control:            ControlHandle;
  2941.     ignore:            BOOLEAN;
  2942.     kind:                INTEGER;
  2943.     r:                    Rect;
  2944.  
  2945. BEGIN
  2946.     CASE GetWRefCon(window) OF
  2947.  
  2948.         rSoundWindow: BEGIN
  2949.             CASE key OF
  2950.  
  2951.                 kEnterKey, kReturnKey: BEGIN
  2952.                     control:= WindowPeek(window)^.ControlList;
  2953.                     WHILE control <> NIL DO BEGIN            {find the default button}
  2954.                         IF GetCRefCon(control) = rPlaySndCntl THEN
  2955.                             SelectButton(control);            {here it is}
  2956.                         control:= control^^.nextControl;
  2957.                     END;
  2958.                     PlaySelectedSnd(SndDocPeek(window), sPlayingMsg);
  2959.                 END;
  2960.  
  2961.                 kUpArrow: BEGIN
  2962.                     SelectNextCell(SndDocPeek(window)^.list, FALSE);
  2963.                     ActivateSndCntls(SndDocPeek(window));
  2964.                 END;
  2965.  
  2966.                 kDownArrow: BEGIN
  2967.                     SelectNextCell(SndDocPeek(window)^.list, TRUE);
  2968.                     ActivateSndCntls(SndDocPeek(window));
  2969.                 END;
  2970.             END;
  2971.         END; {rSoundWindow}
  2972.  
  2973.         rStatusWindow:
  2974.             IF key IN [kEnterKey, kReturnKey, kEscape] THEN BEGIN
  2975.                 SelectButton(WindowPeek(window)^.ControlList);
  2976.                 KillSound;
  2977.             END;
  2978.  
  2979.         rAboutWindow:
  2980.             IF key IN [kEnterKey, kReturnKey, kEscape] THEN BEGIN
  2981.                 SelectButton(WindowPeek(window)^.ControlList);
  2982.                 ignore:= DoCloseWindow(window);
  2983.             END;
  2984.         END; {CASE GetWRefCon(window)}
  2985. END; {DoKeyDown}
  2986.  
  2987. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2988. {$S Main}
  2989. FUNCTION ListClick(sndDoc: SndDocPeek; event: EventRecord): BOOLEAN;
  2990.  
  2991. {Given a document, this will handle any clicking in the list.  The mouse
  2992.  point (event.where) is expected to have been adjusted to the local
  2993.  coordinates of the window.  If this routine does handle the event, then
  2994.  I return TRUE.
  2995.  
  2996.  BUG NOTE: LClick will return a double-click even if no cell was selected.
  2997.  So I have to test for the last click being in a real cell.  If not, then
  2998.  I will not process the double click.  Also, there is another bug in the
  2999.  List Manager.  It will not always deselect the currently selected cell when
  3000.  the user clicks outside of the data bounds.  In other words, sometimes
  3001.  my list would show 4 items when the list has room to show 8.  If the user
  3002.  clicked in the bottom area of the list (below the last item) the List
  3003.  Manager should deselect any items.  It doesn’t all the time, just sometimes.
  3004.  The only real solution would be to write a new LClick.}
  3005.  
  3006. VAR
  3007.     aCell:            Cell;
  3008.     listRect:        Rect;
  3009.  
  3010. BEGIN
  3011.     listRect:= sndDoc^.list^^.rView;
  3012.     listRect.right:= listRect.right + kScrollBarWidth;
  3013.     IF PtInRect(event.where, listRect) THEN BEGIN
  3014.         IF LClick(event.where, event.modifiers, sndDoc^.list) THEN BEGIN
  3015.             aCell:= LLastClick(sndDoc^.list);
  3016.             IF PtInRect(aCell, sndDoc^.list^^.dataBounds) THEN
  3017.                 PlaySelectedSnd(sndDoc, sPlayingMsg);
  3018.         END;
  3019.         ActivateSndCntls(sndDoc);
  3020.         ListClick:= TRUE;                                            {I handled the event}
  3021.     END ELSE
  3022.         ListClick:= FALSE;
  3023. END;
  3024.  
  3025. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3026. {$S Main}
  3027. PROCEDURE DoSndDocClick(sndDoc: SndDocPeek; event: EventRecord);
  3028.  
  3029. {This is called when a mouse-down event occurs in the content of my
  3030.  application windows.  First thing to check for is a click in the list.
  3031.  If not a list click, then find what control may have been clicked in and
  3032.  handle that.}
  3033.  
  3034. VAR
  3035.     control:         ControlHandle;
  3036.  
  3037. BEGIN
  3038.     SetPort(GrafPtr(sndDoc));
  3039.     GlobalToLocal(event.where);
  3040.     IF NOT ListClick(sndDoc, event) THEN BEGIN
  3041.         IF FindControl(event.where, WindowPtr(sndDoc), control) <> 0 THEN BEGIN
  3042.             IF TrackControl(control, event.where, NIL) <> 0 THEN BEGIN
  3043.                 CASE GetCRefCon(control) OF
  3044.  
  3045.                     rPlaySndCntl:
  3046.                         PlaySelectedSnd(sndDoc, sPlayingMsg);
  3047.  
  3048.                     rHyperPlayCntl:
  3049.                         PlaySelectedSnd(sndDoc, sHyperMsg);
  3050.  
  3051.                     rPlayScaleCntl:
  3052.                         PlaySndSong(sndDoc, rScaleSnd);
  3053.  
  3054.                     rMelodyCntl:
  3055.                         PlaySndSong(sndDoc, rMelodyPart1);
  3056.  
  3057.                     rStopCntl:
  3058.                         KillSound;
  3059.  
  3060.                 END; {CASE GetCRefCon(control)}
  3061.             END; {IF TrackControl}
  3062.         END; {IF FindControl}
  3063.     END; {IF NOT ListSelect}
  3064. END; {DoSndDocClick}
  3065.  
  3066. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3067. {$S Main}
  3068. PROCEDURE DoStatClick(statWindow: StatWindowPeek; event: EventRecord);
  3069.  
  3070. {The status window has a stop button.  This will stop any sound in
  3071.  progress.  So, if the user clicks in my status window I need to check
  3072.  for this.}
  3073.  
  3074. VAR
  3075.     control:         ControlHandle;
  3076.  
  3077. BEGIN
  3078.     SetPort(GrafPtr(statWindow));
  3079.     GlobalToLocal(event.where);
  3080.     IF FindControl(event.where, WindowPtr(statWindow), control) <> 0 THEN
  3081.         IF TrackControl(control, event.where, NIL) <> 0 THEN
  3082.             KillSound;
  3083. END;
  3084.  
  3085. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3086. {$S Main}
  3087. PROCEDURE DoAboutClick(window: WindowPtr; event: EventRecord);
  3088.  
  3089. {The about window has a single OK button.  If the users clicks in it, then
  3090.  close the window.}
  3091.  
  3092. VAR
  3093.     control:         ControlHandle;
  3094.     ignore:            BOOLEAN;
  3095.  
  3096. BEGIN
  3097.     SetPort(window);
  3098.     GlobalToLocal(event.where);
  3099.     IF FindControl(event.where, WindowPtr(window), control) <> 0 THEN BEGIN
  3100.         IF TrackControl(control, event.where, NIL) <> 0 THEN
  3101.             ignore:= DoCloseWindow(window);
  3102.     END;
  3103. END;
  3104.  
  3105. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3106. {$S Main}
  3107. PROCEDURE DoUpdate(window: WindowPtr);
  3108.  
  3109. {This is called when an update event is received for any of my windows.  It
  3110.  calls the appropriate window’s update routine to draw its contents.  As an
  3111.  efficiency measure that does not have to be followed, it calls the drawing
  3112.  routine only if the visRgn is non-empty.  This will handle situations
  3113.  where calculations for drawing or drawing itself is very time-consuming.
  3114.  Why does QD give you an update with an empty updateRgn?}
  3115.  
  3116. BEGIN
  3117.     BeginUpdate(window);                                {setup the visRgn, clears updateRgn}
  3118.     IF NOT EmptyRgn(window^.visRgn) THEN BEGIN     {if updating to be done}
  3119.         SetPort(window);                                {set to the current port}
  3120.         CASE GetWRefCon(window) OF                    {call the window’s drawing routine}
  3121.  
  3122.             rSoundWindow:
  3123.                 DrawSndWindow(window);
  3124.  
  3125.             rStatusWindow:
  3126.                 DrawStatusWindow;
  3127.  
  3128.             rAboutWindow:
  3129.                 DrawAboutWindow(window);
  3130.         END;
  3131.     END;
  3132.     EndUpdate(window);                                {restores the visRgn}
  3133. END; {DoUpdate}
  3134.  
  3135. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3136. {$S Main}
  3137. PROCEDURE DoActivate(window: WindowPtr; becomingActive: BOOLEAN);
  3138.  
  3139. {This is called when a window is to be activated or deactivated.  For the
  3140.  document window I activate all the controls and the list.  For the status
  3141.  window I activate the one and only control.  This is also called for
  3142.  suspend and resume events while running MultiFinder.}
  3143.  
  3144. VAR
  3145.     kind:            INTEGER;
  3146.     button:        ControlHandle;
  3147.     r:                Rect;
  3148.  
  3149. BEGIN
  3150.     IF window <> NIL THEN BEGIN
  3151.         CASE GetWRefCon(window) OF
  3152.  
  3153.             rSoundWindow: BEGIN
  3154.                 ActivateSndCntls(SndDocPeek(window));
  3155.                 LActivate(becomingActive, SndDocPeek(window)^.list);
  3156.             END;
  3157.  
  3158.             rStatusWindow: BEGIN
  3159.                 IF becomingActive THEN                            {it only has one control}
  3160.                     HiliteControl(WindowPeek(window)^.ControlList, kCntlActivate)
  3161.                 ELSE
  3162.                     HiliteControl(WindowPeek(window)^.ControlList, kCntlDeactivate);
  3163.                 DoButtonOutline(WindowPeek(window)^.ControlList);
  3164.             END;
  3165.  
  3166.             rAboutWindow: BEGIN
  3167.                 IF becomingActive THEN                            {it only has one control}
  3168.                     HiliteControl(WindowPeek(window)^.ControlList, kCntlActivate)
  3169.                 ELSE
  3170.                     HiliteControl(WindowPeek(window)^.ControlList, kCntlDeactivate);
  3171.                 DoButtonOutline(WindowPeek(window)^.ControlList);
  3172.             END;
  3173.  
  3174.         END;
  3175.     END;
  3176. END; {DoActivate}
  3177.  
  3178. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3179. {$S Main}
  3180. PROCEDURE DoEvent(event: EventRecord);
  3181.  
  3182. {As Spike Lee says, “Do the right thing.” Determine what kind of event it
  3183.  is, and call the appropriate routines.  Key down events are first tested
  3184.  as being command key events for menus or command-. for cancel.  If it’s
  3185.  the command-. the user is asking to cancel the sound.  In this case, if
  3186.  the front window is the status window then the button should look as if it
  3187.  has been clicked.  This is proper human interface.  Any non-menu command
  3188.  keys are passed to DoKeyDown.  I have a global flag, gInModalState, which
  3189.  is used to handle the front window as a modal dialog.  This means I ignore
  3190.  clicks outside of the modal window and menu command keys.  I could have a
  3191.  different global flag that would mean it’s a modal window but uses menu
  3192.  commands, such as gInModalMenuState.  An important note is that I do pass
  3193.  any other non-menu command keys to DoKeys, so the modal window could have
  3194.  access to key events.  One last thing to note happens during a suspend
  3195.  event.   Applications using sound should dispose of their sound channels
  3196.  at suspend time.  No other application can use sound while another one has
  3197.  channels allocated.  To stop my sound, I call KillSound which hides the
  3198.  status window.  MultiFinder does properly deactivate the front window at
  3199.  suspend time and applications normally do not have to worry about
  3200.  HiliteWindow.  I do because the front window could have been the status
  3201.  window and I’ve removed it after getting a suspend event.  This causes the
  3202.  next window, a document window, to become highlighted as the active
  3203.  window.  To avoid my next window from being highlighted while in the
  3204.  background, I have to call HiliteWindow *after* KillSound.  This is
  3205.  strange and only applications changing the front window at suspend event
  3206.  time have to be concerned about this.}
  3207.  
  3208. CONST
  3209. {OSEvent is the event number of the suspend/resume and mouse-moved events
  3210.  sent by MultiFinder.  Once I determine an osEvent has occurred, I look at
  3211.  the high byte of the message sent to determine which kind it is.  To
  3212.  further differentiate suspend and resume events, it is necessary to check
  3213.  the low bit of the message.  I’m using the more efficient MPW bit
  3214.  routines.}
  3215.  
  3216.     osEvt =            app4Evt;        {defined in post MPW 3.0 Events.p}
  3217.     suspendResumeMessage = 1;    {defined in post MPW 3.0 Events.p}
  3218.     kGetHighByte =    24;            {24 bits (three bytes) to shift right}
  3219.     kResumeMask =    1;                {resume event is a 1 in low bit of message}
  3220.  
  3221. VAR
  3222.     window:            WindowPtr;
  3223.     aPoint:             Point;
  3224.     finalTicks:        LongInt;
  3225.     part, err:        INTEGER;
  3226.     ignore:            BOOLEAN;
  3227.     key:                CHAR;
  3228.  
  3229. BEGIN
  3230.     CASE event.what OF
  3231.         mouseDown: BEGIN
  3232.             part:= FindWindow(event.where, window);
  3233.             IF (IsModalWindow(FrontWindow) & (window <> FrontWindow))
  3234.              | (IsModalWindow(FrontWindow) & (part = inMenuBar)) THEN BEGIN
  3235.                 DoErrorSound(1);                            {click outside of modal window}
  3236.                 EXIT(DoEvent);                                {break out of routine}
  3237.             END;
  3238.             CASE part OF
  3239.                 inMenuBar: BEGIN                            {process the menu command}
  3240.                     AdjustMenus;
  3241.                     DoMenuCommand(MenuSelect(event.where));
  3242.                 END;
  3243.  
  3244.                 inSysWindow:                                {let system handle the mouseDown}
  3245.                     SystemClick(event, window);
  3246.  
  3247.                 inContent: BEGIN
  3248.                     IF (window <> FrontWindow) THEN
  3249.                         SelectWindow(window)
  3250.                     ELSE BEGIN
  3251.                         CASE GetWRefCon(window) OF
  3252.  
  3253.                             rSoundWindow:
  3254.                                 DoSndDocClick(SndDocPeek(window), event);
  3255.  
  3256.                             rStatusWindow:
  3257.                                 DoStatClick(StatWindowPeek(window), event);
  3258.  
  3259.                             rAboutWindow:
  3260.                                 DoAboutClick(window, event);
  3261.  
  3262.                             END; {CASE GetWRefCon(window)}
  3263.                         END;
  3264.                     END; {inContent}
  3265.  
  3266.                 inDrag:                        {pass screenBits.bounds to get all gDevices}
  3267.                     DragWindow(window, event.where, screenBits.bounds);
  3268.  
  3269.                 inGoAway: BEGIN
  3270.                     IF TrackGoAway(window, event.where) THEN
  3271.                         ignore:= DoCloseWindow(window);
  3272.                     END;
  3273.  
  3274.             END; {CASE}
  3275.         END; {mouseDown}
  3276.  
  3277.         keyDown, autoKey: BEGIN
  3278.             window:= FrontWindow;
  3279.             key:= CHR(BAnd(event.message, charCodeMask));
  3280.             IF BAnd(event.modifiers, cmdKey) <> 0 THEN BEGIN    {Command key down}
  3281.                 IF key = kPeriod THEN BEGIN
  3282.                     IF window = WindowPtr(gStatusWindow) THEN
  3283.                         SelectButton(WindowPeek(gStatusWindow)^.ControlList);
  3284.                     KillSound;
  3285.                 END ELSE
  3286.                     IF (event.what = keyDown) & (NOT IsModalWindow(window)) THEN BEGIN
  3287.                         AdjustMenus;    {enable/disable/check menu items properly}
  3288.                         DoMenuCommand(MenuKey(key));
  3289.                     END;
  3290.             END ELSE                                                            {non-Command keys}
  3291.                 IF window <> NIL THEN                                    {if there’s a window}
  3292.                     DoKeyDown(key, window);
  3293.         END;
  3294.  
  3295.         activateEvt:                        {TRUE for activate, FALSE for deactivate}
  3296.             DoActivate(WindowPtr(event.message),
  3297.                             BAnd(event.modifiers, activeFlag) <> 0);
  3298.  
  3299.         updateEvt:                            {call DoUpdate with the window to update}
  3300.             DoUpdate(WindowPtr(event.message));
  3301.  
  3302.         diskEvt:                                {Call DIBadMount in response to a diskEvt}
  3303.             IF HiWrd(event.message) <> noErr THEN BEGIN
  3304.                 SetPt(aPoint, kSFLeft, kSFTop);
  3305.                 err:= DIBadMount(aPoint, event.message);
  3306.             END;
  3307.  
  3308.         osEvt: BEGIN
  3309.             CASE BSR(event.message, kGetHighByte) OF    {high byte of message}
  3310.  
  3311.                 suspendResumeMessage: BEGIN
  3312.                     IF BAnd(event.message, kResumeMask) <> 0 THEN
  3313.                         gInBackground:= FALSE                {it was a resume event}
  3314.                     ELSE BEGIN
  3315.                         gInBackground:= TRUE;                {it was a suspend event}
  3316.                         KillSound;                                {stop any sound}
  3317.                         window:= FrontWindow;                {get front window}
  3318.                         IF window <> NIL THEN                 {don’t use a NIL window}
  3319.                             HiliteWindow(window, FALSE);    {then properly activate it}
  3320.                     END;
  3321.                     DoActivate(FrontWindow, NOT gInBackground);
  3322.                 END; {suspendResumeMessage}
  3323.  
  3324.             END; {CASE}
  3325.         END; {osEvt}
  3326.  
  3327.     END; {CASE event.what}
  3328. END; {DoEvent}
  3329.  
  3330. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3331. {$S Main}
  3332. PROCEDURE AdjustCursor(region: RgnHandle);
  3333.  
  3334. {Change the cursor’s shape, depending on its current position.  This also
  3335.  calculates the region where the current cursor resides (for
  3336.  WaitNextEvent).  This is based on its current position in global
  3337.  coordinates.  If the mouse is ever outside of that region, an event is
  3338.  generated causing this routine to be called again by the event loop.  This
  3339.  allows me to change the region to where the mouse is currently located.
  3340.  If there is more to the event than just “the mouse moved,” this gets
  3341.  called before the event is processed to make sure the cursor is the right
  3342.  one.  In any (ahem) event, this is called again before I fall back into
  3343.  WaitNextEvent.  Extreme integer values are used to create a wide open
  3344.  region.  -MAXINT - 1 is the largest negative integer (-32768) and MAXINT
  3345.  is the largest positive integer (32767).
  3346.  
  3347.  BUG NOTE: The largest positive value for a region’s size is MAXINT - 1
  3348.  due to a very old bug that still remains to this day.}
  3349.  
  3350. VAR
  3351.     window:                 WindowPtr;
  3352.     arrowRgn,
  3353.     sndCursorRgn:        RgnHandle;
  3354.     sndCursorRect:        Rect;
  3355.  
  3356. BEGIN
  3357.     window:= FrontWindow;        {I only adjust the cursor when I am in front}
  3358.     IF (NOT gInBackground) & (NOT IsDAWindow(window)) THEN BEGIN
  3359.  
  3360.         arrowRgn:= NewRgn;        {calculate regions for different cursor shapes}
  3361.         sndCursorRgn:= NewRgn;    {start with a big, big rectangular region}
  3362.         SetRectRgn(arrowRgn, -MAXINT - 1, -MAXINT - 1, MAXINT - 1, MAXINT - 1);
  3363.  
  3364.         IF IsDocWindow(window) THEN BEGIN    {calculate region for document cursor}
  3365.             sndCursorRect:= window^.portRect;
  3366.             SetPort(window);
  3367.             WITH sndCursorRect DO BEGIN        {make a global version of the viewRect}
  3368.                 LocalToGlobal(topLeft);
  3369.                 LocalToGlobal(botRight);
  3370.             END;
  3371.             RectRgn(sndCursorRgn, sndCursorRect);
  3372.             WITH window^.portBits.bounds DO
  3373.                 SetOrigin(-left, -top);
  3374.             SectRgn(sndCursorRgn, window^.visRgn, sndCursorRgn);
  3375.             SetOrigin(0, 0);
  3376.         END;
  3377.  
  3378.         DiffRgn(arrowRgn, sndCursorRgn, arrowRgn);    {subtract other region}
  3379.         IF PtInRgn(GetGlobalMouse, sndCursorRgn) THEN BEGIN
  3380.             SetCursor(GetCursor(rSndCursor)^^);         {change cursor and region}
  3381.             CopyRgn(sndCursorRgn, region);
  3382.         END ELSE BEGIN
  3383.             SetCursor(arrow);
  3384.             CopyRgn(arrowRgn, region);
  3385.         END;
  3386.         DisposeRgn(arrowRgn);                {get rid of our local regions}
  3387.         DisposeRgn(sndCursorRgn);
  3388.     END;
  3389. END; {AdjustCursor}
  3390.  
  3391. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3392. {$S Main}
  3393. PROCEDURE EventLoop;
  3394.  
  3395. {Get events forever, and handle them by calling DoEvent.  Since this
  3396.  application requires System 6.0x or later I know that _WaitNextEvent is
  3397.  always there, even without MultiFinder.  MultiFinder’s sleep is used to
  3398.  determine how often I want to receive events, regardless if an event has
  3399.  actually occurred.  In this application, I don’t perform any background
  3400.  processing so I’m being super friendly by using MAXLONGINT as a sleep
  3401.  value.  This also helps keep Virtual Memory from paging me in just to run
  3402.  my event loop and find out that nothing happened.  The application will
  3403.  only be called upon for events that must be handled.  Also call
  3404.  AdjustCursor each time through the loop.  AdjustCursor will return the
  3405.  current region containing the mouse and is passed to WaitNextEvent.  If
  3406.  the mouse travels out of the region, another event is generated.  I have
  3407.  to call AdjustCursor just before doing the event to make sure the right
  3408.  cursor is shown.  Another thing, if I have a sound playing asynchronously
  3409.  then I want to dispose of my channel as soon as possible.  I set up a flag
  3410.  in the SoundUnit that will keep track of when it has a channel allocated.
  3411.  I can call the SndChanOpen function to find out if this is true.  It
  3412.  pretty much like keeping track of when you’re in the background.  If a
  3413.  channel is open, then the MultiFinder sleep time is adjusted to a
  3414.  reasonable time that will allow me to catch when the sound has completed
  3415.  so that I may dispose of my channels and status window.  That’s when I
  3416.  return kPollingSleepTime.}
  3417.  
  3418. VAR
  3419.     cursorRgn:             RgnHandle;
  3420.     event:                 EventRecord;
  3421.     sleep:                LONGINT;
  3422.  
  3423.     total, contig:            LONGINT;
  3424.  
  3425. BEGIN
  3426.     cursorRgn:= NewRgn;                        {1st time pass WNE an empty region}
  3427.     REPEAT
  3428.         IF SndChanOpen THEN                                    {if we’re playing a sound}
  3429.             sleep:= kPollingSleepTime                        {use the polling sleep value}
  3430.         ELSE BEGIN
  3431.             sleep:= MAXLONGINT;                                {default value for sleep}
  3432.             UnloadSeg(@_SoundUnit);                            {unload the Sound Unit}
  3433.             UnloadSeg(@_SANELib);                            {unload the SANE Unit}
  3434.         END;
  3435.         UnloadSeg(@OpenSoundDoc);                            {unload the open code}
  3436.         IF SoundCompletion THEN
  3437.             KillSound;
  3438.         IF LowOnReserve THEN
  3439.             RecoverReserve;
  3440.         AdjustCursor(cursorRgn);                            {get the right cursor}
  3441.         IF WaitNextEvent(everyEvent, event, sleep, cursorRgn) THEN BEGIN
  3442.             AdjustCursor(cursorRgn);                        {get the right cursor}
  3443.             DoEvent(event);
  3444.         END;
  3445.     UNTIL FALSE;                    {loop forever; I quit through Terminate}
  3446. END; {EventLoop}
  3447.  
  3448.  
  3449. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3450. PROCEDURE _DataInit; EXTERNAL;
  3451.  
  3452. {This routine is contained in the MPW runtime library.  It will be placed
  3453.  into the code segment used to initialize the A5 globals.  This external
  3454.  reference to it is done so that we can unload that segment, named %A5Init.}
  3455.  
  3456. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3457. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MAIN PROGRAM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3458. {$S Main}
  3459. BEGIN
  3460.     UnloadSeg(@_DataInit);    {note that _DataInit must not be in Main!}
  3461.  
  3462. {If you have stack requirements that differ from the default, then you
  3463.  could use SetApplLimit to increase StackSpace at this point, before
  3464.  calling MaxApplZone.}
  3465.  
  3466.     MaxApplZone;                {expand the heap so code segments load at the top}
  3467.     Initialize;                    {initialize the program}
  3468.     UnloadSeg(@Initialize);    {note that Initialize must not be in Main!}
  3469.     EventLoop;                    {call the main event loop}
  3470. END.
  3471. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MAIN PROGRAM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3472. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3473.